componentDidUpdate创建了无限循环,但不确定如何避免它



嗨,我正在调用componentdiupdate,以便用新的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)
}
}

我的应用程序的预期行为是,组件挂载获取项目并将其设置为state,然后每当我进行post、update或delete调用时,todos的状态都会发生变化,它会触发fetch调用来重新呈现页面上的todos。然而,我得到了一个无限循环,我该如何解决这个问题?

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

相关内容

最新更新