如何解决状态变量显示值“未定义”,尽管已设置默认值“假”
我创建了一个自定义组件MyCustomList
,它只是FlatList
的包装。有三个道具items
,getMore
,loading
。这篇文章仅关注loading
道具中传递的内容。
const MyCustomList = ({items,getMore,loading}) => {
// console shows 'false'
console.log(loading)
// use the 'loading' as the default value for the state variable
const [isLoading,setIsLoading] = useState(loading);
const myFooter = () => {
// console shows undefined,why? Shouldn't it be the default value 'false'?
console.log(isLoading});
...
}
return (
<FlatList
keyExtractor={keyExtractor}
data={items}
renderItem={renderItem}
onEndReached={getMore}
onEndReachedThreshold={0}
ListFooterComponent={myFooter}
/>
);
...
export default MyCustomList;
}
在上述自定义组件中,父组件传入了loading
道具,其值为false
,在运行时将列表滑动到底部时,将调用myFooter,但状态变量isLoading
为使用值undefined
登录。为什么?
解决方法
仅更改为此
const MyCustomList = ({items,getMore,loading = false}) => {
....
,按如下所示更改您的代码,我们在isLoading
中设置useEffect
状态
import React,{ useState,useEffect } from 'react';//add
const MyCustomList = ({items,loading}) => {
// console shows 'false'
console.log(loading)
// use the 'loading' as the default value for the state variable
const [isLoading,setIsLoading] = useState(loading);
useEffect(() => {
setIsLoading(loading)
},[]);
const myFooter = () => {
// console shows undefined,why? Shouldn't it be the default value 'false'?
console.log(isLoading});
...
}
return (
<FlatList
keyExtractor={keyExtractor}
data={items}
renderItem={renderItem}
onEndReached={getMore}
onEndReachedThreshold={0}
ListFooterComponent={myFooter}
/>
);
...
export default MyCustomList;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。