gpt4 book ai didi

javascript - React Hook "useSelector"在函数中被调用

转载 作者:行者123 更新时间:2023-11-29 10:26:32 25 4
gpt4 key购买 nike

我无法弄清楚“useSelector”发生了什么,我需要一点帮助。

错误

React Hook "useSelector" is called in function "render_user" which is neither a React function component or a custom React Hook function

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);

最佳答案

错误是因为您违反了 rules of hooks :

  • Only Call Hooks at the Top Level
  • Only Call Hooks from React Functions

违规行为:

  1. useSelector() 未在顶层调用。它在 render() 中的 render_user() 中调用(即嵌套函数)。
  2. useSelector() 是类组件的一部分,Navigationbar

你可以提取一个组件来遵循钩子(Hook)的规则并使用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()}</>
}
}

关于javascript - React Hook "useSelector"在函数中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com