当在另一个函数中调用调用它的函数时,React Hooks 状态无法正常工作

React Hooks state not working properly when the function calling it is called in another function

我有这个组件使用 Hooks:

function App() {
  const [text, setText] = useState({ h1: "hello", h2: "hi" });

  const changeH1 = () => {
    setText({
      ...text,
      h1: text.h1 + "C"
    });
  };

  const changeH2 = () => {
    setText({
      ...text,
      h2: text.h2 + "X"
    });
  };

  const changeAll = () => {
    changeH1();
    changeH2();
  };

  return (
    <div className="App">
      <h1 onClick={() => changeH1()}>{text.h1}</h1>
      <h1 onClick={() => changeH2()}>{text.h2}</h1>
      <button onClick={() => changeAll()}>Change</button>
    </div>
  );
}

它将显示两个带有一些文本的标题和一个按钮。当我单击第一个标题时,"C" 字符将添加到标题中。当我单击第二个标题时,"X" 字符将添加到标题中。当我点击按钮时,它会同时做上面两个动作。

它在两个标题上工作正常,但按钮。当我单击该按钮时,只有第二个标题发生变化。我认为 changeH1changeH2setTextchangeAll 中调用时不起作用。我的代码有什么问题?

因为 changeH2() 通过 ...text.

覆盖了 h1 属性

2 setText() 调用在重新渲染之前执行 - 我相信这是由于 https://overreacted.io/react-as-a-ui-runtime/#batching

中解释的批处理

一种解决方案是使用简单状态而不是对象:

  const [h1, setH1] = useState("hello");
  const [h2, setH2] = useState("hi");
  ...

否则 useReducer 进行更复杂的操作 https://reactjs.org/docs/hooks-reference.html#usereducer