【问题标题】:React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook functionReact Hook "useDispatch" 不能在顶层调用。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks
【发布时间】:2021-03-20 12:25:29
【问题描述】:

我正在做的是创建一个带有反应钩子的身份验证系统。但是,当我使用反应组件声明和调用常量时,它会返回以下错误。声明常量和/或函数的正确位置是什么?

错误:无法在顶层调用 React Hook “useDispatch”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用

function handleSubmit({email, password}) {
  dispatch(signInRequest(email, password));
}

const dispatch = useDispatch();



class Login extends React.Component {
  render() {
    return (
      <>
        //Other code here
      </>
    );
  }
}

export default Login;

【问题讨论】:

    标签: reactjs react-redux react-hooks


    【解决方案1】:

    您不能在功能组件之外或在类组件中调用反应钩子。 https://reactjs.org/docs/hooks-rules.html

    
    const Login = () => {
      const dispatch = useDispatch();
      function handleSubmit({email, password}) {
          dispatch(signInRequest(email, password));
      }
      render() {
        return (
          <>
            //Other code here
          </>
        );
      }
    }
    
    export default Login;
    

    【讨论】:

      【解决方案2】:

      您正在使用一个类组件,并且您正在尝试使用永远不会出错的钩子。钩子应该在功能组件内部调用,例如:

      const Login = () => {
       const dispatch = useDispatch();
      
      function handleSubmit({email, password}) {
        dispatch(signInRequest(email, password));
      }
      
          return (
            <>
              //Other code here
            </>
          );
        
      }
      
      export default Login;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-26
        • 2021-11-27
        • 1970-01-01
        • 2023-02-19
        • 1970-01-01
        • 2020-08-26
        • 2019-10-21
        • 2022-08-07
        相关资源
        最近更新 更多