Redux工具包形式转换等待状态更改

2ul0zpep  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(138)

我正在使用redux工具包和thunk从api接收数据。
我需要使用从第一个API调用中获得的数据作为第二个API调用的参数,以连续顺序从2个API中获取数据(首先是search 1,然后是search 2)
为了做到这一点,我需要等待第一个分派完全完成从调用getSearch 1到更新状态的工作。
救命啊!
第一个

3ks5zfa0

3ks5zfa01#

我解决了它就像slideshowp2的共享链接。

useEffect(() => {
    getResult();
  }, [dispatch]);   // listen for dispatch(), should run getResult() twice

  const getResult = async () => {
    let action;
    if (!search1) {   // skip below when called twice
      action = await dispatch(getSearch1(args));
    }
    if (isFulfilled(action)) {
      const id = action.payload.map((item) => item.id.toString());
      dispatch(getSearch2(id ?? []));
    }
  };
ovfsdjhp

ovfsdjhp2#

你可以用.unwrap()方法来实现,参见文档:

try {
    const { data } = await dispatch(getSearch1(args)).unwrap()
    await dispatch(getSearch2(data ?? []));
    // handle result here
  } catch (rejectedValueOrSerializedError) {
    // handle error here
  }

相关问题