【问题标题】:Editing a state array using buttons within a map of the array - react native使用数组映射中的按钮编辑状态数组 - 反应原生
【发布时间】: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


    【解决方案1】:

    这发生在您调用 likePost 设置状态时。它重新渲染组件,它再次调用你的likePost,因为你在渲染方法中调用它,而不是引用它。所以这最终会循环运行。

    我假设您最终不希望将图像详细信息作为状态保留在组件中,而是将其保存在 redux 或 AsyncStorage 上的本地存储中。建议您现在进行该切换,从该组件的状态中删除详细信息,这样您就无需在 likePost 上设置状态,从而停止此无限循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2018-11-09
      • 1970-01-01
      相关资源
      最近更新 更多