useSelector(来自Redux + React)返回undefined。

huangapple go评论59阅读模式
英文:

useSelector (from Redux +React) returns undefined

问题

我正在使用React + TypeScript进行开发,并使用Redux进行集中状态管理 - 以存储当前登录的用户。

这是userReducer:

这是存储:

这是我的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 userReducer:

Here is the store:

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 =&gt; 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&lt;typeof store.getState&gt;

per our TS usage docs:

huangapple
  • 本文由 发表于 2023年6月16日 07:17:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定