英文:
useSelector (from Redux +React) returns undefined
问题
我正在使用React + TypeScript进行开发,并使用Redux进行集中状态管理 - 以存储当前登录的用户。
这是我的React组件中的代码片段,我在其中尝试访问用户状态:
我不确定为什么useSelector
返回undefined,因为我已经在userReducer
中定义了初始状态。
英文:
I am using React + TypeScript for development and using Redux for centralised state management - to store the current user logged in.
Here is the snippet of code inside my React component, where I try to access the user state:
I'm not sure why useSelector
returned undefined since I have defined an initialState in the userReducer
.
答案1
得分: 0
因为您将根状态定义为{user}
。换句话说,userReducer
的数据附加到根状态上,名称为state.user
。
所以,您的选择器需要是state => state.user
。
您的存储文件中还存在问题。您已经创建了另一个带有const rootReducer = combineReducers({userReducer})
的减速器函数,然后从中推断出了RootState
类型。
这有两个问题:
- 那个减速器函数根本没有被使用!
configureStore
已经根据您提供的定义创建了自己的根减速器函数,并正在使用它 - 您的
RootState
类型是错误的,因为它是从错误的函数中推断出来的
这就是为什么您甚至没有在这里收到TS错误的原因。
相反,您需要删除combineReducers
行,然后执行以下操作:
type RootState = ReturnType<typeof store.getState>
根据我们的TS使用文档:
英文:
Because you defined the root state as {user}
. In other words, the userReducer
's data is attached to the root state as state.user
.
So, your selector needs to be state => state.user
.
You also have a problem in your store file. You've created another reducer function with const rootReducer = combineReducers({userReducer})
, and then inferred the RootState
type from that.
That is wrong in two ways:
- That reducer function is not being used at all!
configureStore
already made its own root reducer function from the definition you provided and is using that - Your
RootState
type is wrong, because it's being inferred from the wrong function
That's why you're not even getting a TS error here.
Instead, you need to delete the combineReducers
line, and then do:
type RootState = ReturnType<typeof store.getState>
per our TS usage docs:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论