简体   繁体   中英

How can I change only one value in a React useState that contains an object and assign a different one to the rest?

I have the following State:

const [clickColumn, setClickColumn] = useState({
    name: 0,
    tasks: 0,
    partner: 0,
    riskFactor: 0,
    legalForm: 0,
    foundationYear: 0
  })

And now, for example, I only want to set name to 2 and the rest to 1. But I do not want to write it this way: setClickColumn({ name: 2, tasks: 1, riskFactor: 1, partner: 1, legalForm: 1, foundationYear: 1 });

How can I make it shorter?

You can use spread operator to make it simple:

setClickColumn({ ...clickColumn, name: 2 });

it spreads the existing object clickColumn and adds the name: 2 to it, overriding the default value. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Making it shorter wouldn't necessarily make it more simple, but you can do something like this:

 const obj = { name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }; const entries = Object.entries(obj).map(([key, value]) => key === 'name' ? [key, 2] : [key, 1]); const result = Object.fromEntries(entries); console.log(result);

You can easily create a function that will reset the state for you by parsing the object and give the right value:

 const getResetClickColumn = (clickColumn) => { Object.keys(clickColumn).forEach(key => { const value = (key === 'name' ? 2 : 1); clickColumn[key] = value; }) return clickColumn; } const reset = getResetClickColumn({ name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }) console.log(reset)

In addition to @MorKadosh 's answer:

setClickColumn(Object.fromEntries(Object.entries(clickColumn)
   .map(([key, value]) => [key, key === 'name' ? 2 : 1])))

You can simply make a temp variable

let tmpColumn = clickColumn;
tmpColumn.name = 2;
// other changes
setClickColumn(tmpColumn);

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