Redux 工具包 thunk 等待状态更改

Redux toolkit thunk wait for state change

我正在使用带有 thunk 的 redux 工具包从 api 接收数据。
我需要使用从第一个 api 调用中获得的数据作为第二个 api 调用的参数(先搜索 1,然后搜索 2)[=17],以连续顺序从 2 api 中获取数据=] 为此,我需要等待第一次调度完全完成其从调用 getSearch1 到更新状态的工作。

请帮忙!

// store
import { configureStore } from "@reduxjs/toolkit";
import searchReducer from "./slice/searchSlice";

export const store = configureStore({
  reducer: {
    search: searchReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
// slice
export const getSearch1 = createAsyncThunk(
  "search/getSearch1",
  async (args: string[]) => {
    const result = await ApiUtil.search1(args);
    return result;
  }
);

export const getSearch2 = createAsyncThunk(
  "search/getSearch2",
  async (ids: string[]) => {
    const result = await ApiUtil.search2(ids);
    return result;
  }
);

export const searchSlice = createSlice({
  name: "search",
  initialState,
  reducers: {...},
  extraReducers: (builder) => {
    builder
      .addCase(getSearch1.fulfilled, (state, action) => {
        state.search1 = action.payload;
      })
      .addCase(getSearch2.fulfilled, (state, action) => {
        state.search2 = action.payload;
      });
  },
});
// home page
import {
  ...
  getSearch1,
  getSearch2,
} from "../../redux/slice/searchSlice";

  const handleSearch = () => {
    dispatch(getSearch1(args));
    const ids = search1?.map((item) => item.id.toString());
    dispatch(getSearch2(ids ?? []));
    history.push(ROUTES.RESULT_PAGE, search1);
  };

我按照slideshowp2的分享解决了link。

  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 ?? []));
    }
  };