如何在 React 中等待 useDispatch 值?

aks*_*aks 4 javascript reactjs redux react-redux

在我的 React 代码库中,我已经集成了 Redux 的react-redux使用,并且我正在使用useDispatch钩子从我的视图中分派动作。我只有一个问题,我无法在更新商店后立即访问更新的值。有没有办法让我等待状态更新完成,比如await我可以执行其他代码的回调?

这是我的代码的样子:

import React from 'react';
import { useDispatch } from "react-redux";
import { setCore } from "../store/global";

// the value from the store is drilled down as props
export default function Home({ instance, core }) {
  const dispatch = useDispatch();

  const onConnect = async () => {
    // core may have some value before but I want to clear
    console.log(core); // prints the old value
    await dispatch(setCore(null));
    console.log(core); // Need to have null here
  }

  return (
    <div>
      <button onClick={onConnect}>Connect</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

mar*_*son 9

默认情况下调度是 100% 同步的。无需等待派遣本身。

然而,等待组件的 props 更新是一个完全不同的问题。由于代码,core永远不会更新,因为定义onConnect已经捕获的值core 在定义函数的时间

您可能希望将该部分逻辑移动到一个useEffect()钩子中,该钩子将在 的值core发生变化时触发。