反应导航路由器 v6 无效钩子调用

Ane*_*lie 1 reactjs react-router

我试图在用户登录时重定向我的用户。但是我到目前为止发现的所有方法都不起作用。etg 我正在尝试使用 react router v6 来使用 useNavigate 功能。

但由于某种原因,我收到以下错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See react-invalid-hook-call for tips about how to debug and fix this problem.
Run Code Online (Sandbox Code Playgroud)

在:

/login.jsx:35
let navigate = useNavigate();
Run Code Online (Sandbox Code Playgroud)

功能:

PerformLogin = () => {
  let navigate = useNavigate();
  const username = this.state.username;
  const password = this.state.password;
  if (username === '') {
    console.log("please enter username");
  } else if (password === '') {
    console.log("please enter password");
  } else {
    console.log("username of login: ",this.state.username);
    axios.post(process.env.REACT_APP_DATAURL + `/login`,{ username: username, password: password },{withCredentials: true})
    .then(res => {
      res = res.data;
      console.log(res);
      console.log(res.data);
      if (res.type) {
        console.log("navigating logged in");
        navigate.push('/crime');
        //return <Navigate to="/crime" />;
      }
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

问:我该怎么做才能解决这个问题并能够重定向我的用户?

Ant*_*iad 6

编辑:对于反应路由器 v6

在 react-router v6 中没有withRouternor useHistory。为了简单起见,我建议重构您的组件以使用钩子,但另一种解决方案是创建一个包装器组件,它将从钩子中获得的导航函数作为道具传递:

import { useNavigate } from 'react-router-dom';

class MyComponent extends React.Component {
  //...
    PerformLogin = () => {
        const username = this.state.username;
        const password = this.state.password;
        // ...
        this.props.navigate('/crime');
    }
}

function WithNavigate(props) {
    let navigate = useNavigate();
    return <MyComponent {...props} navigate={navigate} />
}

export default WithNavigate
Run Code Online (Sandbox Code Playgroud)

useHistory 是一个钩子,钩子只能在“功能”组件中使用。

但是我猜你是从“类”组件中使用它的,因为有一些this.state,所以你不能在那里使用钩子。

另一种适合您的方法是将您的组件包装在一个withRouter:

import { withRouter } from "react-router";

class MyComponent extends React.Component {
  //...
    PerformLogin = () => {
        const history = this.props.history;
        const username = this.state.username;
        const password = this.state.password;
        // ...
    }
}

export default withRouter(MyComponent)

Run Code Online (Sandbox Code Playgroud)

withRouter 将历史作为道具注入。