【问题标题】:How to deal with the dependency between two async thunks如何处理两个异步 thunk 之间的依赖关系
【发布时间】:2021-07-05 01:13:14
【问题描述】:

我有两个由createAsyncThunk()redux-toolkit 函数创建的异步thunk。

例如

const getOrder = createAsyncThunk('a/getOrder', async (_, thunkAPI) => {
  // `userId` from API.getUser()
  // I tried to get the `userId` from redux store, but got `undefined`.
  const user = thunkAPI.getState().user;
  const userId = user.userId;

  const response = await APIs.getOrder(userId);
  return response.result;
});

const getUser = createAsyncThunk('a/getUser', async () => {
  const response = await APIs.getUser();
  return response.result;
});

在组件中,我同时调度了这两个异步 thunk。

useEffect(() => {
  dispatch(getUser());
  dispatch(getOrder());
}, []);

getOrder thunk 取决于 getUser() thunk 的结果。获取userId 参数的正确方法是什么?我可以从 redux 商店 user 切片状态中获取 userId 吗?

【问题讨论】:

    标签: reactjs redux redux-toolkit


    【解决方案1】:

    我可以从redux store用户切片状态中获取userId吗?

    您可以访问 thunk 中的状态,但如果 userId 尚不存在,则无法获取它。

    如果必须先完成对 APIs.getUser() 的调用,然后才能开始对 APIs.getOrder(userId) 的调用,那么同时对 dispatch 进行两个 thunk 是没有意义的。


    我建议getOrderuserId 作为参数。你可以从await获取userId-ing第一个dispatch的分辨率。

    import { isFulfilled } from "@reduxjs/toolkit";
    
    useEffect(() => {
      const load = async () => {
        // is either a fulfilled or rejected action
        const action = await dispatch(getUser());
        if (isFulfilled(action)) {
          dispatch(getOrder(action.payload.userId));
        }
      };
      load();
    }, [dispatch]);
    

    或者,您可以在单独的 useEffectdispatch 第二个操作,该操作取决于从状态中选择的 userId 变量。

    // is initially undefined, but then becomes an id
    const userId = useSelector(state => state.user?.userId);
    
    const dispatch = useDispatch();
    
    // call getUser on mount
    useEffect(() => {
      dispatch(getUser());
    }, [dispatch]);
    
    // call getOrder after you already have a userId
    useEffect(() => {
      if (userId) {
        dispatch(getOrder(userId));
      }
    }, [dispatch, userId]);
    

    【讨论】:

      【解决方案2】:

      在这种情况下,我将创建第三个可以处理异步结果的 thunk,即某种包装器/帮助器 thunk。 order 和 user getter thunk 应该尽可能少。在第三个 thunk 中,您可以根据响应和您想要使用的任何其他内容实现任何复杂的逻辑,并等到您返回用户,然后使用所需的参数调用 order api 端点。

      【讨论】:

        猜你喜欢
        • 2021-03-12
        • 2014-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-14
        • 2015-11-06
        • 1970-01-01
        • 2021-02-16
        相关资源
        最近更新 更多