【发布时间】:2020-09-06 18:59:35
【问题描述】:
我是 ReactJS 的新手。当我尝试从一个页面导航到另一个页面时,我坚持使用 React 路由 history.push('/newpage') 对我不起作用。登录服务调用成功我想导航到另一个页面。
我使用的是以下版本
“反应”:“^16.13.1”, “反应域”:“^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 并不起作用。
让我知道我错过了什么。
【问题讨论】:
-
试试 this.props.history.push('/path')
-
@VyasArpit:尝试使用 this.props.history.push('/path');不管用。在类组件中,我们不能使用历史记录
标签: javascript reactjs react-redux react-router