如何编辑状态数组中的项目? [英] How to edit an item in a state array?

查看:39
本文介绍了如何编辑状态数组中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的状态:

this.state = {
  ids: ['A', 'E', 'C']
};

我将如何修改状态以便将索引 1 处的E"更改为B"?例如:

How would I go about modifying the state so that 'E' at index 1 is changed to 'B'? Like for example:

this.setState({
  ids[1]: 'B'
});

这将如何完成?

推荐答案

我的建议是习惯使用不可变操作,这样你就不要修改内部状态对象.

My suggestion is to get used to use immutable operations, so you don't modify internal state object.

正如 react 文档中所指出的:

永远不要直接改变 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.

在这种情况下,您可以[1]使用slice() 获取数组的新副本[2]操作副本,然后 [3] setState 与新的 Array.这是一个很好的做法.

In this case, you can [1] use slice() to get a new copy of the Array, [2] manipulate the copy, and, then, [3] setState with the new Array. It's a good practice.

类似的东西:

const newIds = this.state.ids.slice() //copy the array
newIds[1] = 'B' //execute the manipulations
this.setState({ids: newIds}) //set the new state

这篇关于如何编辑状态数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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