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

Rok*_*tSe 5 reactjs react-redux react-hooks

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

错误:无法在顶层调用 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;
Run Code Online (Sandbox Code Playgroud)

Shu*_*rma 6

您不能在功能组件外部或类组件中调用反应钩子。 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;
Run Code Online (Sandbox Code Playgroud)