useState Hook 不获取数据
useState Hook not taking data
我正在尝试将状态设置为我从 Redux 获得的道具。我有一个数组,props.feed
,在控制台上显示一个数组。但是将我的状态设置为这个数组不会改变状态,它仍然是未定义的,并且它不会呈现我的平面列表,因为数据是未定义的。
如果我登录 props.feed
就可以了。如果我在使用 setPosts
后记录我的状态 posts
,则挂钩不会获取数据。
function FeedScreen(props) {
const [posts, setPosts] = useState([]);
const imageWidth = Math.floor(useWindowDimensions().width);
useEffect(() => {
if (
props.usersFollowingLoaded == props.following.length &&
props.following.length != 0
) {
props.feed.sort((x, y) => {
return x.creation - y.creation;
});
console.log("Props Feed", props.feed);
setPosts(props.feed);
console.log("Posts of friends", posts);
}
}, [props.usersFollowingLoaded, props.feed]);
return (
<View style={styles.container}>
<View style={styles.containerGallery}>
<FlatList
numColumns={1}
data={posts}
horizontal={false}
renderItem={({ item }) => (
<View style={styles.containerImage}>
<Text style={styles.container}>
{item.user.name}
</Text>
<Image
style={styles.image}
source={{ uri: item.downloadURL }}
/>
<Text
onPress={() =>
props.navigation.navigate("Comments", {
postId: item.id,
uid: item.user.uid,
})
}
>
View comments...
</Text>
</View>
)}
/>
</View>
</View>
);
}
这是控制台。
您误解了 React.useState
(和渲染)的工作原理。
当您调用 setPosts
时,它不会立即将 posts
设置为该值。它告诉 React “我希望 posts
等于 <this value>
”,React 将使用更新后的状态变量 稍后 重新渲染您的组件。
至于你的 FlatList 没有渲染列表,那是另一个问题。是自己写的组件吗?
我正在尝试将状态设置为我从 Redux 获得的道具。我有一个数组,props.feed
,在控制台上显示一个数组。但是将我的状态设置为这个数组不会改变状态,它仍然是未定义的,并且它不会呈现我的平面列表,因为数据是未定义的。
如果我登录 props.feed
就可以了。如果我在使用 setPosts
后记录我的状态 posts
,则挂钩不会获取数据。
function FeedScreen(props) {
const [posts, setPosts] = useState([]);
const imageWidth = Math.floor(useWindowDimensions().width);
useEffect(() => {
if (
props.usersFollowingLoaded == props.following.length &&
props.following.length != 0
) {
props.feed.sort((x, y) => {
return x.creation - y.creation;
});
console.log("Props Feed", props.feed);
setPosts(props.feed);
console.log("Posts of friends", posts);
}
}, [props.usersFollowingLoaded, props.feed]);
return (
<View style={styles.container}>
<View style={styles.containerGallery}>
<FlatList
numColumns={1}
data={posts}
horizontal={false}
renderItem={({ item }) => (
<View style={styles.containerImage}>
<Text style={styles.container}>
{item.user.name}
</Text>
<Image
style={styles.image}
source={{ uri: item.downloadURL }}
/>
<Text
onPress={() =>
props.navigation.navigate("Comments", {
postId: item.id,
uid: item.user.uid,
})
}
>
View comments...
</Text>
</View>
)}
/>
</View>
</View>
);
}
这是控制台。
您误解了 React.useState
(和渲染)的工作原理。
当您调用 setPosts
时,它不会立即将 posts
设置为该值。它告诉 React “我希望 posts
等于 <this value>
”,React 将使用更新后的状态变量 稍后 重新渲染您的组件。
至于你的 FlatList 没有渲染列表,那是另一个问题。是自己写的组件吗?