简体   繁体   English

如何避免改变this.state或redux对象

[英]how to avoid mutating this.state or redux object

For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object. 例如,如果我想对this.state或某个其他对象(例如Object.keys(this.state).map()执行任何操作,以访问该对象中的所有值。

Is it bad practice to do this? 这样做是不好的做法吗?

Object.keys(this.state).map(k => this.state[k]);

Thanks 谢谢

In React, you should only mutate this.state using this.setState() so that React knows when to re-render components. 在React中,您只应使用this.setState() this.state this.setState()以便React知道何时重新渲染组件。

The line of code you've written is fine, because you're not actually modifying the state object. 您编写的代码行很好,因为您实际上并没有在修改状态对象。 You've already created a new array using Object.keys . 您已经使用Object.keys创建了一个新数组。

If however, you want to copy this.state without modifying it, try the following. 但是,如果您要复制this.state而不进行修改,请尝试以下操作。

const state = {...this.state};

// Or 

const state = Object.assign({}, this.state);

React Mutating State. 反应突变状态。

let state = {
    age    : 25,
    name   : 'Robin',
    friends: ['Barney', 'Ted']
}

Change Age 改变年龄

this.setState({age: 26}) 

Change Name 更换名字

this.setState({name: 'Lily'}) 

Add Friend 添加好友

this.setState({ 
    friends: this.state.friends.concat(['Marshall'])
})

Try this library immutability-helper for complex state updates. 尝试使用此库不变性帮助器进行复杂的状态更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM