ReactJS:为什么我不应该改变嵌套状态? [英] ReactJS: Why shouldn't I mutate nested state?

查看:38
本文介绍了ReactJS:为什么我不应该改变嵌套状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于 setState 的 ReactJS 文档.具体来说,这一行:

I've read the ReactJS documentation about setState. Specifically, this line:

永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变.将 this.state 视为不可变的.

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

但在我的代码中,我做这样的事情:

But in my code, I do things like this:

var x = this.state.x;
x.y.z.push("foo"); // z is a list
this.setState({x:x});

此代码似乎可以正常工作并正确更新状态.但是根据文档,我违反了规则.这种方法有什么问题?是否存在性能问题?比赛条件?我会被 Facebook 开发团队骂吗?理想情况下,我希望避免使用不变性助手和所有其他疯狂行为并保持简单.

This code seems to work and update state correctly. But according to the documentation, I'm breaking the rules. What's the problem with this approach? Are there performance issues? Race conditions? Will I be scolded by the Facebook dev team? Ideally, I'd like to avoid the immutability helpers and all the other craziness and keep things simple.

推荐答案

原因是你错过了与 this.setState 关联的回调,他们声称你可以通过分配来覆盖数据直奔对象.

The reason is that you miss out on the callbacks associated with this.setState and they claim that you may overwrite data by just assigning straight to the object.

另外,通常在 OOP 中(我不知道 JS 得到了多少颗星...)你会使用 getter 和 setter 方法而不是直接操作对象.在这个例子中通过 this.state.prop1 = "xyz";

Also, often in OOP (I don't know how many stars JS gets...) you'll use getter and setter methods instead of directly manipulating the object. In this example via this.state.prop1 = "xyz";

我从来没有反应覆盖我直接设置的状态属性.以这种方式编码的诱惑可能是在不重新渲染的情况下写入状态.但是,如果您这样做,您可能会考虑无论如何不要将它们置于状态.

I've never had react overwrite my directly set state properties. The temptation to code it this way may be write to state without re-rendering. But if you're doing that you may think about not putting those in state anyways.

如果重新渲染性能是一个问题,请查看 https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

If re-rendering performance is an issues checkout https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

这篇关于ReactJS:为什么我不应该改变嵌套状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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