我试图在用户登录时重定向我的用户。但是我到目前为止发现的所有方法都行不通。我试图通过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.
在:
/login.jsx:35
let navigate = useNavigate();
功能:
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" />;
}
})
}
}
问:如何解决此问题并能够重定向用户?
在反应路由器V6也没有withRouter
,也没有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
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)
withRouter将历史记录作为道具。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句