Why doesn't spread attributes work with React useState hook

mottosson :

I'm keeping state in a functional component using the useState hook and want to update a single value without having to explicitly set all other attributes, so I thought using the spread operator would work, but it does not!

This is my state:

const [state, setState] = useState({
  data: [],
  currentIndex: 0,
  editMode: false
});

Can someone explain why this doesn't work...

setState({ editMode: value, ...state });

...when this does:

setState({ editMode: value, data: [], currentIndex: 0 });

Whats the difference? Can I use the spread operator or have I misunderstood something?

Here is a CodeSandbox example to demonstrate the issue.

user9408899 :

Just reverse the order:

setState({ ...state, editMode: value });

Otherwise, you are overwriting editMode's value with the old value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29737&siteId=1