【问题标题】:componentDidUpdate creates infinite loop and not sure how to avoid itcomponentDidUpdate 创建无限循环,不知道如何避免它
【发布时间】:2021-03-22 17:59:15
【问题描述】:

您好,我正在调用 componentdidupdate,以便像这样使用新的 ToDo 重新呈现我的页面


        this.state = {
            displayToDos: false,
            displayLanding: true,
            todo: {
                title: '',
                task: ''
            },
            todos: [],
            createdToDo: null,
            updateModal: false
        }
    }

    async componentDidMount() {
        this.fetchItems()
    }

    componentDidUpdate(prevState) {
        if (prevState.todos !== this.state.todos) {
            this.fetchItems()
        }
    }

    fetchItems = async () => {
        try {
            const todos = await getItems()
            this.setState({ todos })
            console.log('set state of todos', this.state.todos)
        } catch (err) {
            console.error(err)
        }
    }


我对我的应用程序的预期行为是组件挂载获取项目并将它们设置为状态,然后每当我发帖、更新或删除调用 todos 更改的状态并触发获取调用以重新渲染页面上的待办事项。但是我得到一个无限循环,我该如何解决这个问题?

【问题讨论】:

  • 因为todos 是一个数组并且对数组的引用发生了变化,所以componentDidUpdate 总是触发fetchItem
  • if (prevState.todos !== this.state.todos) 使用循环将其更改为单个项目检查
  • 您好,感谢您的解释,但我仍然很困惑抱歉...,我将如何实施循环?

标签: javascript reactjs react-native frontend backend


【解决方案1】:

您可以像这样比较数组: let arraysEqual = JSON.stringify(todo) == JSON.stringify(todo1); 或者我会建议你使用这个库Loadsh 您可以使用.isEqual 方法检查数组。

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2021-08-26
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多