useState挂接设置器错误地覆盖状态

2022-02-22 00:00:00 reactjs javascript react-hooks

问题是:我试图通过单击按钮来调用2个函数。这两个函数都会更新状态(我使用的是useState挂钩)。第一个函数将value1正确更新为"new 1",但是在1s(SetTimeout)之后,第二个函数激发,它将值2更改为"new 2",但是!它将值1设置回"1"。为什么会发生这种事? 提前感谢!

import React, { useState } from "react";

const Test = () => {
  const [state, setState] = useState({
    value1: "1",
    value2: "2"
  });

  const changeValue1 = () => {
    setState({ ...state, value1: "new 1" });
  };
  const changeValue2 = () => {
    setState({ ...state, value2: "new 2" });
  };

  return (
    <>
      <button
        onClick={() => {
          changeValue1();
          setTimeout(changeValue2, 1000);
        }}
      >
        CHANGE BOTH
      </button>
      <h1>{state.value1}</h1>
      <h1>{state.value2}</h1>
    </>
  );
};

export default Test;

解决方案

欢迎来到关闭地狱。出现此问题的原因是,无论何时调用setStatestate都会获得新的内存引用,但函数changeValue1changeValue2由于闭包关系,会保留旧的初始state引用。

保证setStatechangeValue1changeValue2获取最新状态的解决方案是使用callback(以之前的状态为参数):

import React, { useState } from "react";

const Test = () => {
  const [state, setState] = useState({
    value1: "1",
    value2: "2"
  });

  const changeValue1 = () => {
    setState((prevState) => ({ ...prevState, value1: "new 1" }));
  };
  const changeValue2 = () => {
    setState((prevState) => ({ ...prevState, value2: "new 2" }));
  };

  // ...
};

您可以找到有关此关闭问题的更广泛讨论here和here。

相关文章