javascript - 使用历史推送反应路由器导航
问题描述
我是 ReactJS 的新手。当我尝试从一个页面导航到另一个页面时,我坚持使用 React 路由 history.push('/newpage') 对我不起作用。登录服务调用成功我想导航到另一个页面。
我正在使用以下版本
“react”:“^16.13.1”,“react-dom”:“^16.13.1”,“react-router-dom”:“^5.2.0”,
import React, { Component } from 'react';
import { useHistory } from 'react-router-dom';
import '../Login/Login.css';
import {Auth} from '../../services/Api';
// import { Redirect } from 'react-router-dom'
class Login extends Component {
constructor(props) {
super(props)
this.state = {
userName: '',
password: ''
}
this.changeEventReact = this.changeEventReact.bind(this);
this.login = this.login.bind(this);
}
changeEventReact = (e) =>{
this.setState({[e.target.name]: e.target.value});
// console.log(this.state);
}
login = e=>{
// console.log(this.state);
Auth('login', this.state)
.then((result)=>{
let responseJSON = result;
if(responseJSON.data.id != ''){
console.log("Login success");
const history = useHistory();
let path = `/facilityRegister`;
history.push(path);
}else{
console.log('Login failed');
}
});
}
我们可以使用以下三种方法来做到这一点
1. history.push('/facilityRegister')
2. <Redirect to='/facilityRegister'/>
3. window.location.href("/facilityRegister')
window.location.href 正在按预期工作。但是 history.push 并不起作用。
让我知道我错过了什么。
解决方案
根据反应常见问题解答:
你不能在类组件中使用 Hooks
这就是为什么const history = useHistory();
不在这里工作的原因。但无论如何,你不能在异步函数中使用钩子。改用withRouter HOC 或尝试将您的组件重写为功能。
推荐阅读
- python - 从txt文件存储数据的最简单方法?
- typescript - 子实体与基础实体不兼容 [typescript]
- cuda - NSight Compute 显示什么是不受“支持”的停顿原因?
- javascript - React 原生分享内容,如 TikTok 个人资料页面分享
- html - 为什么在顶行和中间行使用 rowspan 时中间行会消失?
- javascript - S3Client AWS 上传进度
- spring-boot - 带有 Springboot 和应用程序的 Liquibase-
.yml 为例如 level = prod 创建 sql - mvvm - 如何订阅 ReactiveUI 中可观察集合中的嵌套属性
- r - 如何使用部分文件名将 CSV 文件读入 R?
- java - 使用 Microsoft 身份验证时无法在 TWA 中隐藏 url 栏