小编典典

将参数传递给异步 redux 操作时出错

javascript

我正在尝试使用 redux 工具包创建一个抓取应用程序以用于学习目的,但是每当我在调度语句中传递自定义参数时抓取过程都会失败,但在 thunk 中传递默认参数时可以正常工作我的异步 thunk

export const loadData = createAsyncThunk(
  "alldata/getdata",
  async ({ pageNo, language }, thunkAPI) => {
    const data = await fetch(
      `http://localhost:5000/scrape?pageNo=${encodeURIComponent(
        pageNo
      )}&language=${encodeURIComponent(language)}`
    );
    const json = data.json();
    return json;
  }
);

我的切片

const projectSlice = createSlice({
  name: "allprojects",
  state: {
    projectState: [],
    workingState: [],
    isLoading: false,
    hasError: false,
  },
  reducers: {
    addProject: (state, action) => {
      return state.workingState.push(action.payload);
    },
    removeProject: (state, action) => {
      return state.workingState.filter(
        (project) => project.id !== action.payload.id
      );
    },
  },
  extraReducers: {
    [loadData.pending]: (state, action) => {
      state.isLoading = true;
      state.hasError = false;
    },
    [loadData.fulfilled]: (state, action) => {
      const { json } = action.payload;
      state.isLoading = false;
      state.hasError = false;
    },
    [loadData.rejected]: (state, action) => {
      state.isLoading = false;
      state.hasError = true;
    },
  },
});

export const { addProject, removeProject } = projectSlice.actions;
export const { Projectreducer } = projectSlice.reducer;
export const selectAllPosts = (state) => state.allprojects.projectState;

调用异步操作

React.useEffect(() => {
    console.log(dispatch(loadData(1, "ruby")));
  }, []);
//url:https://github.com/search?p=undefined&q=language%3Aundefined

我该如何解决这个错误


阅读 172

收藏
2022-07-25

共1个答案

小编典典

异步 thunk 参数必须收集在一个对象中:

dispatch(loadData({ pageNo: 1, language: "ruby" }))
2022-07-25