首页 > 解决方案 > 如何使用 Redux 建立商店

问题描述

我正在尝试让我的 redux 使用新的表单功能,现在当我尝试显示我的主页时收到此错误消息。index.reducer 文件最初包含我用于身份验证的教程中的 auth 和 message reducer,之前工作正常,所以我没有包含它们的 reducer。

我是否以正确的方式使用 configureStore index.reducer 文件中的五个减速器,还是必须放入 combineReducer 函数?

错误信息

Error: Expected the reducer to be a function.

index.reducer.js

export default configureStore({
    // combine the reducers
    reducer: {
        user: userReducer,
        fields: fieldsReducer,
        diveSchool: diveSchoolReducer,
        auth,
        message
    }
});

store.js

const middleware = [thunk];

const store = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(...middleware))
    +  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;

用户.reducer.js

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

export const userSlice = createSlice({
    name: 'user',
    initialState: {
        dives: [],
    },
    reducers: {
        // expects action creator to be called with a dive object
        addDive: (state, action) => {
            // append to the dives array
            state.dives.push(action.payload)
        },
        deleteDive: (state, action) => {
            // append to the dives array
            state.dives.push(action.payload)
        }
    }
})

export const { addDive } = userSlice.actions;
export const { deleteDive } = userSlice.actions;
export default userSlice.reducer;

fields.reducer.js

export const fieldsSlice = createSlice({
    name: 'diveLogFields',
    initialState: {
        current: [],
        region: [],
        diveType: [],
        visibility: [],
        diveSpot: [],
    },
    reducers: {},
    extraReducers: {
        // picks up the success action from the thunk
        // [requireData.fulfilled.type]: (state, action) => {
        //     // set the property based on the field property in the action
        //     state[action.payload.field], action.payload.items
        // }
    }
})

export default fieldsSlice.reducer;

标签: reactjsredux

解决方案


您正在使用@reduxjs/toolkit. 当你调用configureStore函数时,它会返回 store。你正试图把这个商店作为一个 reducercreateStore从 redux 中放入。使用工具包,您不应该使用createStore. 您已经从index.reducer.js. 将它传递给提供者,你就设置好了。


推荐阅读