当我在 componentWillUpdate
中 setState
时,componentWillUpdate
在无限循环中运行,并且不会停止触发。
这永远不会让我的渲染有机会反射(reflect)我的更改。如果我不应该使用 componentWillUpdate
,如何更改状态?
编辑:我已经了解了 setState
不应该在 componentWillUpdate 中调用。我只是很困惑我应该做什么作为替代方案。
编辑 #2:我从 componentWillReceiveProps
开始,但当我的父组件更改状态时,我似乎无法触发此函数。我将 parent 的状态作为 Prop 提供给我的 child 。
最佳答案
首先要做的是检查此方法的官方文档 ( link )。您可以在其中阅读函数实际调用的时间。
然后阅读常见错误(注释):
You cannot use this.setState() in this method. If you need to update state in response to a prop change, use componentWillReceiveProps instead.
您更改状态,React 会自动调用 componentWillUpdate
。
关于javascript - 如果我不应该在 componentWillUpdate 中调用 setState,如何更新状态(使用 ReactJS)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945089/