简体   繁体   中英

React update state hook on functional component does not allow dot notation

I'm getting the following error:

Parsing error: Unexpected token, expected ","

In my functional component (not class) I have:

  const [ ministries, setMinistries ] = useState({
    options: '',
    selected: ''
  });

later in another method I try to update ministries by doing the following:

let opts = [1, 2, 3, 4];

setMinistries({
  ministries.selected: opts
})

Assuming ministries is the object and selected is in ministries I would expect dot notation. ministries.selected: opts to work.

What am I doing wrong?

Please, be aware that the useState updater overwrite a previous state with a new one and it does not perform any merging. Instead, it requires you to pass the complete state each time.

However, that's not the case with this.setState in a class component .

That's something that, to my advice, is important to remember to avoid subtle undesired behavior.

So, the correct way to update your state would be:

setMinistries(prevMinistries => ({
   ...prevMinistries,
   selected: opts
}));

You can't do ministries.selected as an object key.

You can just do:

setMinistries({
  selected: opts,
});
setMinistries({
  ministries.selected: opts
})

This is bad syntax. You call the property of the object within an object.

Try

setMinistries({
  ministries: {
    selected: opts
  }
})

or

setMinistries({
  selected: opts
})

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