Redux Toolkit报错:类型'{ counter: CounterState; }'无'userReducer'属性
解决Redux Toolkit中"Property 'userReducer' does not exist on type '{ counter: CounterState; }'"错误
问题核心
这个类型错误的本质是Redux Store的state结构与你在useAppSelector中访问的路径不匹配,同时类型定义存在缺失或偏差。
修复步骤
修正Store的Reducer注册
你的setupStore中使用了rootReducer,但代码未展示其定义。必须确保rootReducer包含userSlice的reducer,且键名与后续访问路径一致:// 若userSlice在当前文件或已导入 const rootReducer = { // 键名"user"对应store.state中的user字段 user: userSlice.reducer // 如有其他reducer(如counter),也在此处添加 }调整useAppSelector的访问路径
当前代码中state.userReducer是错误路径,因为你的slice名称为user,且rootReducer中注册的键名是user,应改为:const { count } = useAppSelector(state => state.user)确保RootState类型正确推导
RootState必须从实际Store实例自动推导,不能手动凭空定义,否则会出现类型不匹配:// 先创建Store实例 export const store = setupStore() // 从Store的getState方法推导RootState类型 export type RootState = ReturnType<typeof store.getState> // 推导AppDispatch类型 export type AppDispatch = typeof store.dispatch // 重新定义useAppDispatch export const useAppDispatch = () => useDispatch<AppDispatch>() // 保留useAppSelector的定义 export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector修正拼写错误(可选但推荐)
代码中inrement是拼写错误,正确应为increment,否则dispatch时会找不到对应action:// slice中的reducer修正 reducers: { increment(state, action: PayloadAction<number>) { state.count += action.payload; } } // 组件中调用修正 const { increment } = userSlice.actions <button onClick={() => dispatch(increment(10))}>Increment</button>
内容的提问来源于stack exchange,提问作者Kamilpro
相关产品推荐
相关产品推荐

