为什么我必须像 "state.topicsReducer.topics" 一样访问我的 Redux 状态?
Why do I have to access my Redux state like "state.topicsReducer.topics"?
我已经使用 @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' 这样的状态访问。我是不是在我的选项变量中搞砸了什么?
谢谢!
确保像这样将 reducers
对象传递给 combineReducers(reducers) or configureStore:
combineReducers({ topics: topicsReducer });
// or
configureStore({ reducer: { topics: topicsReducer } })
状态形状将为 { topics }
。然后你可以像这样创建选择器:
export const selectTopics = state => state.topics;
我已经使用 @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' 这样的状态访问。我是不是在我的选项变量中搞砸了什么?
谢谢!
确保像这样将 reducers
对象传递给 combineReducers(reducers) or configureStore:
combineReducers({ topics: topicsReducer });
// or
configureStore({ reducer: { topics: topicsReducer } })
状态形状将为 { topics }
。然后你可以像这样创建选择器:
export const selectTopics = state => state.topics;