简体   繁体   中英

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?

You can use the functional setState syntax and create a copy using map to prevent mutation of the current state.

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) 
          };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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