React 从 useEffect 中的 Redux 存储中获取状态 [英] React get state from Redux store within useEffect
问题描述
从 useEffect
钩子内的 Redux 存储中获取状态的正确方法是什么?
What is the correct way to get state from the Redux store within the useEffect
hook?
useEffect(() => {
const user = useSelector(state => state.user);
});
我试图在 useEffect
中获取当前状态,但我无法使用 useSelector
调用,因为这会导致错误说明:
I am attempting to get the current state within useEffect
but I cannot use the useSelector
call because this results in an error stating:
Invariant Violation:Hooks 只能在函数组件内部调用.
我想我明白为什么它违反了钩子的主要规则之一.
I think I understand why as it breaks one of the primary rules of hooks.
通过查看 Redux 文档上的 示例,他们似乎使用了 selectors.js
文件来收集当前状态,但这引用了我认为不再需要的 mapStateToProps
.
From reviewing the example on the Redux docs they seem to use a selectors.js
file to gather the current state but this reference the mapStateToProps
which I understood was no longer necessary.
我是否需要创建某种应该在 useEffect
钩子中调用的getter"函数?
Do I need to create some kind of "getter" function which should be called within the useEffect
hook?
推荐答案
您可以将 useSelector
与其他钩子一起放在组件的顶部:
You can place useSelector
at the top of your component along with the other hooks:
const MyComponent = () => {
...
const user = useSelector(state => state.user);
...
}
然后你就可以在你的useEffect
s中访问user
.
Then you can access user
inside your useEffect
s.
这篇关于React 从 useEffect 中的 Redux 存储中获取状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!