【发布时间】:2018-07-31 14:20:54
【问题描述】:
我在子组件中有下面的 JSX。
<td>
<div>
{this.props.image_element}
</div>
</td>
我在父组件中有function,如下所示
image_element= (image_name) => {
if(image_name) {
this.update_photostatus('image');
}
else {
console.log('hello');
this.update_photostatus('input');
}
}
和
update_photostatus = value => {
this.setState({photostatus: value});
}
我在console 中得到的输出如下所示
和
【问题讨论】:
-
您介意与我们分享您的组件吗?
-
正如错误所说,您正在错误的生命周期阶段更新状态,这意味着
setState()触发了render()并且您已经渲染了组件,因此它会导致第二个错误。跨度> -
如果我理解您的代码,您可以在方法 render() 中调用方法 image_element,而方法 image_element 调用 setState()。在文档中写道:“感谢 setState() 调用,React 知道状态已更改,并再次调用 render() 方法以了解屏幕上应该显示的内容。” reactjs.org/docs/state-and-lifecycle.html 会导致无限循环。
-
请不要只发布组件的片段。很难这样理解。问题似乎是您在您的孩子中呈现
this.props.image_element,这可能是从父级传递的函数,将被视为无状态功能组件。因此,如果在渲染过程中调用了该函数,它将导致调用setState(),这在渲染过程中是不允许的。这将导致无限的更新周期。
标签: reactjs react-state-management