【发布时间】:2021-08-04 22:02:22
【问题描述】:
我正在尝试将状态设置为从 Redux 获得的道具。我有一个数组props.feed,在控制台上显示一个数组。但是将我的状态设置为这个数组并不会改变状态,它仍然是未定义的,并且它不会呈现我的 Flatlist,因为数据是未定义的。
如果我登录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>
);
}
这是控制台。
【问题讨论】:
-
它确实改变了状态,你只是不会通过直接记录它来看到它。
posts仍将在下一次渲染时更新为该 3 元素数组,这或多或少会立即发生。那么除了console.log的输出与您的预期不同之外,实际的问题是什么? -
问题实际上是Flatlist。它应该在 Flatlist 的 data 属性中获取一个数组,并且在重新渲染时确实从帖子中获取该数组。所以这很好。 Flatlist 的 renderItem 属性应该在 data 属性上渲染每个迭代,但不知何故将整个数组作为项并变得未定义。
标签: javascript react-native use-state