所以这是我的状态:
this.state = { ids: ['A', 'E', 'C'] };
我将如何修改状态,以使索引1的“ E”更改为“ B”?例如:
this.setState({ ids[1]: 'B' });
怎么做?
我的建议是习惯使用不可变的操作,因此您不必修改内部状态对象。
正如react文档中指出的那样:
切勿直接更改this.state,因为之后调用setState()可能会替换您所做的更改。 将此this.state视为不可变的。
在这种情况下,您可以 [1] 用于slice()获取Array 的 新副本 , [2] 操作该副本,然后使用新的Array [3] setState。这是一个好习惯。
slice()
像这样:
const newIds = this.state.ids.slice() //copy the array newIds[1] = 'B' //execute the manipulations this.setState({ids: newIds}) //set the new state