React useState with object 更新对象中的几个状态

React useState with object update several states in object

如何才能只更改对象 useState 中的几个状态? 例如:

const [team, setTeam] = useState({
manager: "",
captain: "",
goalkeeper: "",
defender: "" })

现在我只想同时更新价值经理和守门员。这怎么可能?

我试过了:

setTeam({ ...team, manager: newValue });
setTeam({ ...team, captain: newValue2 });

但它只更新其中一个。

我也试过:

 setTeam({ ...team, manager: newValue, captain: newValue2 });

没用。

是否可以只更改 useState 对象中一定数量的变量?

感谢您的帮助!

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

要实现您期望的行为,您需要执行以下操作:

setTeam(prevState => {
  // Object.assign would also work
  return {...prevState, manager: newValue, captain: newValue2 };
});

您可能还想考虑使用 useReducer,因为您的状态有多个子值,useState 通常最好与单值状态一起使用。

您可以在这里阅读更多内容:https://reactjs.org/docs/hooks-reference.html#usestate

试试这个:

setTeam(currentState => ({
  ...currentState,
  manager: 'Thom',
  goalkeeper: 'Jan'
}))