简体   繁体   English

如何在 ReactJs 的 setState 方法中访问数组的特定索引?

[英]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.

相关问题 如何在 ReactJS 中更新对象的 setstate - How can I updating setstate for object in ReactJS 如何将数组的索引传递到reactJs onClick中? - How can I pass the index of an array into a reactJs onClick? 我如何将 setState 中的数据传递给模态 REACTJS - How can i pass the data inside setState to modal REACTJS 如何设置自动播放轮播中使用的数组的当前索引的State,以作为prop传递到另一个组件中? - How can I setState of the current index of an array being used in a carousel which autoplays, to be passed into another component as a prop? 如何在 reactjs 中设置特定参数的特定值 - How to setState a specific value of a particular parameter in reactjs 我怎样才能在嵌套数组中设置state - How can I setState of in a nested array 如何为嵌套数组和对象设置setState? - How can I setState for the nested array and objects? 如何设置状态并将对象推送到数组? - How can I setState and push object to array? reactjs、setState、Interface props 和 Interface state 之间的关系相对于 typescript,如何使用 setState? - relation between reactjs ,setState, Interface props and Interface state with respect to typescript , how can I use setState? 如何在ReactJS中使用setState()方法? - How should one use the setState() method in ReactJS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM