如果我不应该在componentWillUpdate中调用setState,如何更新状态(使用ReactJS)? [英] How do I update the state (using ReactJS) if I should not call setState in componentWillUpdate?

查看:240
本文介绍了如果我不应该在componentWillUpdate中调用setState,如何更新状态(使用ReactJS)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setState in componentWillUpdate 时, componentWillUpdate 运行在一个不会停止被触发的无限循环中。

When I setState in componentWillUpdate, componentWillUpdate runs in an infinite loop that doesn't stop getting triggered.

这永远不会让我的渲染有机会反映我的变化。如果我不使用 componentWillUpdate ,我该如何更改状态?

This never gives my render a chance to reflect my changes. How can I change the state if I shouldn't use componentWillUpdate?

编辑:我已经有了一些了解不应在componentWillUpdate中调用 setState 。我只是把我应该做的事情弄糊涂了。

I already have some understanding that setState should not be called in componentWillUpdate. I'm just confused what I should do as an alternative.

编辑#2:我开始使用 componentWillReceiveProps 但我的父组件似乎无法触发此功能改变状态。我提供父母的那种状态作为我孩子的道具。

Edit #2: I started with componentWillReceiveProps but I can't seem to trigger this function when my Parent component changes state. I provide that state from the parent as a props to my child.

推荐答案

要做的第一件事就是查看官方文档方法(链接)。实际调用该函数时可以读取的位置。

First thing to do is to check official documentation for this method (link). Where you can read when the function is actually called.

然后读常见错误(注释):

Then read common mistake(note):


您不能在此方法中使用this.setState()。如果您需要更新状态以响应道具更改,请改为使用componentWillReceiveProps。

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

You change the state and React automatically calls componentWillUpdate.

这篇关于如果我不应该在componentWillUpdate中调用setState,如何更新状态(使用ReactJS)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆