简体   繁体   中英

How can I change boolean value in objects?

I have such situation: There is an array:

const arr = [
    { 
      id: 0,
      title: 'a',
      status: false
    },
    { 
      id: 1,
      title: 'a',
      status: false
    },
    { 
      id: 2,
      title: 'a',
      status: false
    },
]

Then I use this array in my React component to get values, but here I also need to change status to true or false in current element (not for all objects)

arr.map(el => {
    return (
        <div key={el.id}>
            <div onClick={() => !status}>{div.title}</div> // here
        </div>
    )
})

So how can I make this?

You can try:

const handleClick = (el) => () => {
  el.status = !el.status
}

arr.map(el => {
    return (
        <div key={el.id}>
            <div onClick={handleClick(el)}>{div.title}</div> // here
        </div>
    )
})

Maintain array in react state;


const [arr,setArr]=useState([
    { 
      id: 0,
      title: 'a',
      status: false
    },
    { 
      id: 1,
      title: 'a',
      status: false
    },
    { 
      id: 2,
      title: 'a',
      status: false
    },
])

Write a function to handle the change in state

const changeStatus =id=>{
  const newArr = arr.map((el,index)=>{
      if(el.id===id){
         return {...el,status:!el.status}
      }
      else return;
     })
   setArr(newArr)
}

call this function on onClick.

arr.map(el => {
    return (
        <div key={el.id}>
            <div onClick={() => changeStatus(el.id)}>{div.title}</div> // here
        </div>
    )
})

How about simply (if you have the access to the arr variable) you have an option of getting an index of the array as the 2nd parameter in the map function.

arr.map((el, ix) => {
    return (
        <div key={el.id}>
            <div onClick={() => { 
              arr[ix].status = !arr[ix].status
             }}>{div.title}</div> // here
        </div>
    )
})

or pull it out in a function (better way) as

function handleClick (ix) {
const currentStatus = arr[ix].status
arr[ix].status = !currentStatus
}

arr.map((el, ix) => {
    return (
        <div key={el.id}>
            <div onClick={() => handleClick(ix)}>{div.title}</div> // here
        </div>
    )
})

EDIT: Didn't see it was a reactJS, my bad, in that case the best case is to manage it with state.

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