【发布时间】:2021-04-08 20:39:58
【问题描述】:
我正在尝试为课程制作一种 Instagram 克隆(不需要后端)。我制作了一个简化的副本来演示我的问题,并将在问题的底部提供它。我正在使用map 函数来显示所有帖子,这些帖子存储在sampleArray 中,在这种情况下是一个状态变量。我想在按下按钮时在帖子中添加一个赞,但立即做出反应会引发错误(#185 缩小):Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. 我的问题是,我怎样才能避免这个问题并达到预期的反效果?如果需要,我可以重新设计我的应用程序的整个结构,因为它很小。由于我是初学者,因此也非常感谢任何其他建议。提前谢谢你。
state = {
sampleArray: [
{imgURL: "https://picsum.photos/200/300", likes: 5, index: 0},
{imgURL: "https://picsum.photos/201/301", likes: 3, index: 1},
],
}
likePost = (i) => {
let tempPost = this.state.sampleArray;
tempPost[i].likes += 1;
this.setState({
sampleArray: tempPost,
});
}
render() {
return (
<View style={styles.container}>
<ScrollView>
{this.state.sampleArray.map((post) => (
<View style={styles.postContainer}>
<Image
source={{ uri: post.imgURL }}
style={{ height: 140, width: 200 }}
/>
<Button
title="Like Post" onPress={this.likePost(post.index)}
/>
</View>
))}
</ScrollView>
</View>
);
}
【问题讨论】:
标签: arrays react-native state