开发者问题收集

如何从 createSlice @reduxjs/toolkit 导入 Reducer 到 store.js

2022-05-10
972

如何使用 createSlice @reduxjs/toolkit 从 todosSlice 导出 todos Reducer 以及如何使用 configureStore 将其导入到存储

这是我的 todosSlice 文件:

    //todosSlice file
    import {createSlice} from '@reduxjs/toolkit';
    const todosSlice = createSlice({
       name: 'todos',
       initialState: [],
       reducers: {
          addTodos: (state, action) => {
             state.push(action.payload)
          },
          removeTodos: (state, action) => {
             state.filter(todo => todo.id !== action.payload.id)
          }
       }
    });
    
    export const { addTodos, removeTodos } = todosSlice.actions;
    export default todosSlice.reducer; //this reducer that i want to import to store file

这是我的存储文件:

    import {configureStore} from '@reduxjs/toolkit';
    //and here is supposed where the reducer imported

    const store = configureStore({
       reducer: {
          todos: //here todos reducer should be.
          anyReducer: anyReducer,
       }
    });
    
    export default store;
1个回答

TodosSlice 中的 export default 语句允许您使用所需名称导入函数。以下是您可以执行的操作。

import {configureStore} from '@reduxjs/toolkit';
import todosReducer from 'path/to/your/TodosSlice';

const store = configureStore({
   reducer: {
      todos: todosReducer,
      anyReducer: anyReducer,
   }
});
paulin-crtn
2022-05-10