迁移到 ReduxToolKit 2.0 和 Redux 5.0 后,我在 extraReducer 和 createSlice 中遇到了一些困难(我仍然是初学者)

问题描述 投票:0回答:1

这是我的 formSlice,在构建器和箭头函数的右括号之后我得到了预期的表达式

import { createAsyncThunk, createReducer, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

export const getform = createAsyncThunk("form/getForm", async () => {
  try {
    const result = await axios.get("http://localhost:5000/autoroute/");
    return result.data;
  } catch (error) {}
});

export const addform = createAsyncThunk("form/add", async (form) => {
  try {
    const result = await axios.post("http://localhost:5000/autoroute/", form);
    return result.data;
  } catch (error) {}
});

export const deleteform = createAsyncThunk("form/deleteForm", async (id) => {
  try {
    const result = await axios.delete(`http://localhost:5000/autoroute/${id}`);
    return result.data;
  } catch (error) {}
});

export const updateform = createAsyncThunk(
  "form/deleteForm",
  async ({ id, form }) => {
    try {
      const result = await axios.put(`http://localhost:5000/autoroute/${id}`, form);
      return result.data;
    } catch (error) {}
  }
);

createReducer(initialState, builder = {
  form: [],
  status: null,
});

export const formSlice = createSlice({
  name: "form",
  initialState,
  reducers: {},
  extraReducers: builder =>{
    builder.getform(pending, (state) => {
      state.status = "pending";
    }),
    builder.getform(pending, (state) => {
      state.status = "success";
    }),
    builder.getform(pending, (state) => {
      state.status = "fail";
    }),
  },
});

// Action creators are generated for each case reducer function
// export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default formSlice.reducer;

它表示在 extrareducers 的右括号构建器之后预期的表达式 我正在开发旧版本的 reduxtoolkit,但错误表明我需要将我的代码与新版本相匹配

reactjs react-redux redux-toolkit
1个回答
0
投票

您的代码中有相当多令人困惑的无效 JavaScript,以下是更正的相关部分:

// I don't know what you wanted to do with createReducer here but it seems you wanted to declare an initial state?
const initialState = {
  form: [],
  status: null,
};

export const formSlice = createSlice({
  name: "form",
  initialState,
  reducers: {},
  extraReducers: builder => {
    // instead of builder.getform(pending 
    builder.addCase(getform.pending, (state) => {
      state.status = "pending";
    }); // you can either do a semicolon here, or nothing, but not a comma
    // this is not an object definition, but a function body.
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.