为什么访问Redux状态需写state.topicsReducer.topics而非state.topics?
问题原因说明
这个topicsReducer层级和你createSlice的options配置没有关系,是你在配置Redux根Store时定义的reducer挂载key决定的。
当你调用configureStore注册slice对应的reducer时,reducer配置项的键名就是根state下对应的字段名,比如你的配置大概率是如下写法:
import { configureStore } from '@reduxjs/toolkit' import topicsSlice from './你的slice文件路径' export const store = configureStore({ reducer: { // 这里的键名决定了访问根state时的前缀 topicsReducer: topicsSlice.reducer } })
如果想要实现state.topics直接访问,只需要把这里的键名改成topics即可:
reducer: { topics: topicsSlice.reducer }
补充说明
很多初学者容易混淆createSlice的name参数和根store的挂载key:
createSlice的name参数仅用于自动生成action的类型前缀,比如你当前配置下addTopic对应的action类型为topics/addTopic,和根state的字段无关- 另外你当前的
addTopicreducer写法可以简化,RTK内置了Immer支持无需手动返回 immutable 结构:
addTopic: (state, action) => { state.topics[action.payload.id] = action.payload }
内容的提问来源于stack exchange,提问作者JasonP789
相关产品推荐
相关产品推荐

