ExtraReducers在redux-toolkit中不工作

xesrikrc  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(183)

我使用redux-toolkit库安装了redux store。
这是index.ts

const createStore = () =>
  configureStore({
    reducer: rootReducer,
    devTools: false,
    middleware: getDefaultMiddleware => {
      const middleware = getDefaultMiddleware({
        immutableCheck: false,
        serializableCheck: false,
      });
      if (process.env.NODE_ENV !== "production") {
        middleware.push(logger);
      }
      return middleware;
    },
  });

export const store = createStore();
export const persistor = persistStore(store);

字符串
这是rootReducer.ts

import { combineReducers, Reducer, AnyAction } from "@reduxjs/toolkit";
import storage from "redux-persist/lib/storage";
import { persistReducer } from "redux-persist";
import userCompnaySlice from "./slices/userCompnaySlice";

const userCompanyDataPersistConfig = {
  key: "userCompanyData",
  storage,
};

const appReducer = combineReducers({
  userCompany: persistReducer(userCompanyDataPersistConfig, userCompnaySlice.reducer),
});

export type RootState = ReturnType<typeof appReducer>;

const rootReducer: Reducer = (state: RootState, action: AnyAction) =>
  appReducer(state, action);

export default rootReducer;


这是userCompanySlice.ts:

import { createSlice } from "@reduxjs/toolkit";
import { userCompanyReducer } from "../../utils/types/reducerStateTypes";
import { getCompanyInfo } from "../thunks/userCompanyThunk";

const initialState: userCompanyReducer = {
  userInfo: {},
  companyInfo: {},
};

const userCompanySlice = createSlice({
  name: "userCompany",
  initialState,
  reducers: {
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
    },
    setCompanyInfo: (state, action) => {
      state.companyInfo = action.payload;
    },
  },
  extraReducers: {
    [getCompanyInfo.pending.type]: (state, action) => {
        console.log("pending");
    },
    [getCompanyInfo.fulfilled.type]: (state, action) => {
        console.log("fulfilled");
      state.companyInfo = action.payload;
    },
    [getCompanyInfo.rejected.type]: (state, action) => {
        console.log("rejected");
    },
  },
});

export const { setUserInfo, setCompanyInfo } = userCompanySlice.actions;

export default userCompanySlice;


这是userCompanyThunk.ts文件:

import { createAsyncThunk } from "@reduxjs/toolkit";
import axiosApiInstance from "../../services/axios";
import { companyAPI } from "../../shared/api/apiRoutes";

export const getCompanyInfo = createAsyncThunk(
  "userCompany/getCompanyInfo",
  async () => {
    try {
      const response = await axiosApiInstance.get(companyAPI);
      console.log(response.data["data"]);
      console.log("Action type:", getCompanyInfo.fulfilled.type);
      return response.data["data"];
    } catch (e: any) {
    //   if (e.response.status >= 400 && e.response.status < 599) {
    //     throw new Error(e.response.data.message);
    //   }
    console.log(e);
    }
  }
);


现在,当我调用getCompanyInfo时,它会成功执行&并打印响应。但在userCompanySlice.ts中的extraReducers中不会调用此功能。
下面是我执行getCompanyInfo的方式:

useEffect(() => {
  console.log("get company");
  dispatch(getCompanyInfo());
  getCompany();
}, [dispatch]);


该函数在useEffect中执行,并打印从API获得的响应,但不调用extraReducer。因此,状态不会更新。
我希望extraReducers在调用getCompanyInfo时工作,并设置companyInfo状态。
我在以前的项目中使用过类似的方法&只是复制粘贴到这个项目中,但由于某些原因,它在这里不起作用。

uplii1fm

uplii1fm1#

你好更新你额外的reducers语法如下

extraReducers: (builder) => {
    builder
    .addCase(getCompanyInfo.pending.type, (state, action) => {
      console.log("pending");
    })
    
  },

字符串

nukf8bse

nukf8bse2#

你好我想更新你的代码额外的reducer代码。下面是一个例子

import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    decrement: (state) => state - 1,
  },
  extraReducers: (builder) => {
    builder
      .addCase(someAction, (state, action) => {
        // Handle the additional action
      })
      .addCase(anotherAction, (state, action) => {
        // Handle another additional action
      });
  },
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;

字符串

相关问题