N
N
nivaech2019-03-10 08:56:59
JavaScript
nivaech, 2019-03-10 08:56:59

How to quickly change a lot of state values?

There is a component with set of the states connected among themselves. If the boolean value of one state changes to true, then all others must become false, for example. Is it possible to somehow select a set of states at a time and give them the desired boolean value, so as not to prescribe the states one by one and not assign the same value to each?

showWindow1= () => {
    this.setState(() => {
      return {
        openWindow1: true,
        openWindow2: false,
        openWindow3: false,  
        openWindow4: false,
        openWindow5: false
      }
    })
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-03-10
@nivaech

this.setState(state => ({
  ...Object.keys(state).reduce((acc, n) => (acc[n] = false, acc), {}),
  свойствоКотороеДолжноБытьTrue: true,
}));

or
this.setState(state =>
  Object.fromEntries(Object.keys(state).map(n => [ n, n === 'свойствоКотороеДолжноБытьTrue' ]))
);

But probably all these boolean properties should be removed in a separate object - you most likely have something else besides them in the state.
Well, such a moment is still not very clear - but can only one property always be true? If it is always true, then you do not need a lot of properties, a single one is enough, which will not be boolean, but a number / string containing the id / index / name of the entity that is currently true.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question