简体   繁体   中英

How do i use setState to update an object inside an array

This is the structure of my state object

this.state = {
    navTabs: [
       {
         name: "Overview",
         isActive: true,
         clickHandler: (ev) => {
           this.setState(...);
         }
       },
       {
         name: "Projects",
         isActive: false,
         clickHandler: (ev) => {
           this.setState(...);
         }
       }
    ]
}

I would like to change the isActive value of each object when the user clicks a navigation tab. Please how can I do this?

navTab html 元素上的onClick处理程序中,您需要调用this.setState({ isActive: <value here> })

  1. Keep you data clean first, Write a single handler function:

     navTabs: [ { name: "Overview", isActive: true }, { name: "Projects", isActive: false } ]
  2. Depending on the requirement write your clickHandler . I am doing toggling in below code

    clickHandler = ()=>{ const updatedState ==this.state.navTabs.map(navTab=>({...navTab,isActive:!navTab.isActive})) this.setState({ navTabs:updatedState }) }
  3. Give it a try your isActive will get toggler, but then ultimately it depends on your requirement. If you are passing your navTabs as props to a child component and clicking on a particular navTab, then logic and code will be different.

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