【发布时间】: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