复杂状态未正确更新

Complex state not updating correctly

问候语:

我认为我没有正确更新我的复杂状态:

export const App = () => {
  const [combos, setCombos] = useState({
    combo1: { data: [1, 2, 3, 4, 5], selected: "" },
    combo2: { data: [8, 9, 10, 11, 12], selected: "" }
  });
  return (
    <div>
      <button  onClick={() => setCombos((ps) => ({ ...ps, combo1: { selected: "" }}}>
        Click Me
      </button>
      <div>
        Combo 1 has a "data" key:{combos.combo1.hasOwnProperty("data") ? "Yes" :No"}
      </div>
    </div>
  );
};

如何正确更新此状态?谢谢!

https://codesandbox.io/s/intelligent-ellis-qi97k?file=/src/App.js

设置状态时,您还必须在 combo1 属性 中使用扩展运算符。如果您仅更新选定的 属性.

,数据 属性 将会丢失
export const App = () => {
  const [combos, setCombos] = useState({
    combo1: { data: [1, 2, 3, 4, 5], selected: "" },
    combo2: { data: [8, 9, 10, 11, 12], selected: "" }
  });
  return (
    <div>
      <button  onClick={() => setCombos((ps) => ({ ...ps, combo1: { ...ps.combo1, selected: "" }}}>
        Click Me
      </button>
      <div>
        Combo 1 has a "data" key:{combos.combo1.hasOwnProperty("data") ? "Yes" :No"}
      </div>
    </div>
  );
};