本文介绍了反应钩子“useSelector"在函数中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法弄清楚useSelector"发生了什么,我需要一点帮助.
I cannot figure out what going on with "useSelector" I need little help, please.
错误
React Hook "useSelector" 在函数 "render_user" 中调用,该函数既不是 React 函数组件,也不是自定义的 React Hook 函数
class Navigationbar extends Component {
onLogoutClick = e => {
e.preventDefault();
this.props.logoutUser(); //this.props.
};
render() {
const render_user = () => {
const auth = useSelector(state => state.auth); Error Message is here
//More Code Here
);
};
}
Navigationbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ logoutUser }
)(Navigationbar);
推荐答案
该错误是由于您违反了 钩子规则:
The error is due to the fact that you violated the rules of hooks:
- 仅在顶层调用挂钩
- 仅从 React 函数调用钩子
违规行为:
useSelector()
不在顶层调用.它在render()
中的render_user()
中调用(即嵌套函数).useSelector()
是类组件的一部分,Navigationbar
useSelector()
is not called in top-level. It is called inrender_user()
inrender()
(i.e nested function).useSelector()
is part of a class component,Navigationbar
你可以提取一个组件来遵循钩子的规则并使用useSelector
:
You can extract a component to follow the rules of hooks and make use of useSelector
:
function User() { // Rule 2: call hooks in function component
const auth = useSelector(state => state.auth); // Rule 1: call hooks in top-level
return <>{auth}</>
}
class Navigationbar extends Component {
render_user() {
if (props.authenticated) {
return <User />
}
// not yet authenticated
// do something else
}
render() {
return <>{this.render_user()}</>
}
}
这篇关于反应钩子“useSelector"在函数中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!