【问题标题】:Redux toolkit thunk wait for state changeRedux 工具包 thunk 等待状态更改
【发布时间】:2022-01-06 19:19:59
【问题描述】:

我正在使用带有 thunk 的 redux 工具包从 api 接收数据。
我需要使用从第一个 api 调用获得的数据作为第二个 api 调用的参数(首先是 search1,然后是 search2),以连续顺序从 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);
  };

【问题讨论】:

标签: reactjs typescript redux redux-thunk redux-toolkit


【解决方案1】:

我解决了它就像 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 ?? []));
    }
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2020-01-29
    • 2021-11-21
    • 2023-01-16
    • 1970-01-01
    • 2021-06-11
    • 2018-04-19
    • 2019-12-04
    相关资源
    最近更新 更多