React Hook “useSelector” is called in function

。_饼干妹妹 提交于 2020-01-14 17:20:23

问题


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:

  1. useSelector() is not called in top-level. It is called in render_user() in render() (i.e nested function).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!