当函数中多次调用钩子时,钩如何工作



为什么true的加载状态永远不会记录下来,而是在下面的collocesand box中yn andnc async时登录?在函数中调用同一钩时发生了什么事?

代码

codesandbox

function App() {
  const [loadingWithUseState, setLoadingWithUseState] = useState(false);
  const [loadingWithReducer, setLoadingWithReducer] = useReducer(
    (acc, next) => ({ ...acc, ...next }),
    { loadingWithReducer: false }
  );
  const onClickWithUseState = () => {
    setLoadingWithUseState(true);
    setLoadingWithUseState(false);
  };
  const onClickWithReducer = () => {
    setLoadingWithReducer({ loadingWithReducer: true });
    setLoadingWithReducer({ loadingWithReducer: false });
  };
  const onClickWithUseStateAsync = async () => {
    setLoadingWithUseState(true);
    await delay();
    setLoadingWithUseState(false);
  };
  const onClickWithReducerAsync = async () => {
    setLoadingWithReducer({ loadingWithReducer: true });
    await delay();
    setLoadingWithReducer({ loadingWithReducer: false });
  };
  useEffect(() => {
    console.log("loadingWithUseState changed to", loadingWithUseState);
  }, [loadingWithUseState]);
  useEffect(() => {
    console.log("loadingWithReducer changed to", loadingWithReducer);
  }, [loadingWithReducer]);
  console.log("re-render", { loadingWithUseState, ...loadingWithReducer });
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={onClickWithUseState}>
        {" "}
        trigger load with useState{" "}
      </button>
      <button onClick={onClickWithReducer}>
        {" "}
        trigger load with useReducer{" "}
      </button>
      <button onClick={onClickWithUseStateAsync}>
        {" "}
        trigger load with async useReducer{" "}
      </button>
      <button onClick={onClickWithReducerAsync}>
        {" "}
        trigger load with async useReducer{" "}
      </button>
    </div>
  );
}

p.s我想建立一个心理模型,即当您将多个挂钩称为

时会发生什么

设置状态时,出于性能原因将状态更新批量。因此,当您致电setLoadingWithUseState(true)然后是setLoadingWithUseState(false)时,React会将这两个批处理在一起,因此您不会看到第一个更新。

相关内容

  • 没有找到相关文章