简体   繁体   中英

React useState - update all object values to true

I have defined an object as follows in a file:

export const items = {
  first: false,
  second: false,
  third: false
}

I'm using it in a component as follows:

import { items } from 'file';
const [elements, setElements] = useState(items);

I have a method which gets called when a button is clicked - the method should change the all the values in elements to true

Using the following changes the values but it does not trigger a re-render of the component (which is what I need)

Object.keys(elements).forEach(element => elements[element] = true);

How can I use setElements to update all the values in elements ?

The problem you are facing is that you are mutating the state object, which means that at the end, prevState === nextState and React bails out of rendering. An option is to use a new object and copy the props like this, using the same combo of Object.keys and forEach but adding an extra step:

setState(prevState => {
  const nextState = {}
  Object.keys(prevState).forEach(key => {
    nextState[key] = true
  })
  return nextState
})

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