[英]how can I access a specific index of an array in the setState method in ReactJs?
For example if a state is like this例如,如果一个状态是这样的
state={
reports:[{name:'nadib',age:23},{name:'nadib2',age:24}]
}
how can I change nadib2
to john with setState method?如何使用 setState 方法将nadib2
更改为 john?
You can use the functional setState
syntax and create a copy using map
to prevent mutation of the current state.您可以使用functional setState
语法并使用map
创建副本以防止当前状态的突变。
Then inside the loop, return the original object if you do not wish to modify.然后在循环内,如果您不想修改,则返回原始对象。 For the object that you need to modify, you could find it with a ternary operator and copy all existing keys, optionally modifying the other keys like shown.对于您需要修改的对象,您可以使用三元运算符找到它并复制所有现有键,可选择修改其他键,如图所示。
this.setState(prevState => {
return {
reports : prevState.reports.map(item =>
item.name === 'nadib2' ? ({...item, name: 'john'}) : item)
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.