我已经使用@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)或像这样配置urestore:
combineReducers({ topics: topicsReducer });
// or
configureStore({ reducer: { topics: topicsReducer } })
状态形状为{ topics }
。然后你可以创建这样的选择器:
export const selectTopics = state => state.topics;