【问题标题】:Why do I have to access my Redux state like "state.topicsReducer.topics"?为什么我必须像“state.topics Reducer.topics”一样访问我的 Redux 状态?
【发布时间】:2021-10-22 04:08:26
【问题描述】:

我已经使用 @reduxjs/toolkit 中的 createSlice 成功创建了一个 redux 存储,如下所示:

const initialState = {
    topics: {
        '123': {
            id: '123',
            name: 'example topic',
            icon: 'icon url',
            quizIds: ['456']
          }
    }
}

const options = {
    name: 'topics',
    initialState: initialState,
    reducers: {
        addTopic: (state, action) => {
            return {
                ...state,
                topics: {
                    ...state.topics,
                    [action.payload.id]: action.payload
                }
            }
        }
    }
}

在创建选择器时,我发现我必须执行以下操作:

export const selectTopics = state => state.topicsReducer.topics;

为什么我需要“topicsReducer”?在我的课程中,我总是看到像“state.topics”这样访问的状态。我在选项变量中搞砸了什么吗?

谢谢!

【问题讨论】:

    标签: javascript react-redux redux-toolkit


    【解决方案1】:

    确保将reducers 对象传递给combineReducers(reducers)configureStore,如下所示:

    combineReducers({ topics: topicsReducer });
    
    // or
    
    configureStore({ reducer: { topics: topicsReducer } })
    

    状态形状将为{ topics }。然后你可以像这样创建选择器:

    export const selectTopics = state => state.topics;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 2017-01-25
      • 2021-12-12
      相关资源
      最近更新 更多