gpt4 book ai didi

javascript - componentDidUpdate 创建无限循环并且不确定如何避免它

转载 作者:行者123 更新时间:2023-12-05 06:55:53 24 4
gpt4 key购买 nike

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


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 的状态就会发生变化,它会触发获取调用以重新呈现页面上的待办事项。但是我得到了一个无限循环,我该如何解决这个问题?

最佳答案

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

关于javascript - componentDidUpdate 创建无限循环并且不确定如何避免它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65249323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com