问题
I cannot figure out what going on with "useSelector" I need little help, please.
ERROR
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);
回答1:
The error is due to the fact that you violated the rules of hooks:
- Only Call Hooks at the Top Level
- Only Call Hooks from React Functions
Violations:
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
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()}</>
}
}
回答2:
useSelector is new hook that is added by react-redux after the addition of new Hooks API to react.
These hooks can only be used in function component
来源:https://stackoverflow.com/questions/57764122/react-hook-useselector-is-called-in-function