如果浏览器历史记录未定义,如何使用 react-router-dom 重定向?



在我的登录组件中,我使用 Axios 向我的 Laravel API 发出请求,如果请求成功,则会存储一个"令牌"cookie,我用它来说明用户是否已登录。 但是,在用户登录后,我希望他被重定向到另一个页面。 我尝试使用浏览器历史记录和this.props.history重定向,但没有任何效果。

这是我得到的错误:

Login.js:33 Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
at Login.js:33

这是我的代码,你能帮我找出问题所在吗?

import React, { Component} from 'react'
import {browserHistory} from 'react-router-dom'
import HomepageNavigation from '../../components/navigation/HomepageNavigation';
import Button from '../../components/Button';
import Axios from 'axios';
import ErrorLine from '../../components/ErrorLine'
import * as Cookies from 'js-cookie'
export class Login extends Component {
constructor(props) {
super(props);
this.state = {email: '', password: ''}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(e) {
e.preventDefault();
Axios.post('http://localhost:8000/api/login', {email: this.state.email, password: this.state.password}, {headers : {Accept: 'application/json'}})
.then((success) => {
Cookies.set('token', success.data.data.token);
browserHistory.push("/")
}, (error) => {
this.setState({'errors' : error.response.data.data})
});
}
render() {
return (
<div className="container fullheight">
<HomepageNavigation />
<div className="columns has-text-centered">
<div className="column is-vcentered is-4 is-offset-4 is-10-mobile is-offset-1-mobile">
<h1 className="title">Connexion</h1>
<img src={require('../../img/logo.svg')}></img>
<form className="login-form user-form fullbox-form" onSubmit={this.handleSubmit}>
<input name="email" value={this.state.email} onChange={this.handleChange} type="text" placeholder="Adresse email"></input><br />
<input name="password" value={this.state.password} onChange={this.handleChange} type="password" placeholder="Mot de passe"></input><br />
{(this.state.errors != undefined) ? Object.keys(this.state.errors).map((key, index) => (<ErrorLine>{this.state.errors[key]}</ErrorLine>)) : ""}
<Button type="primary">Se connecter</Button>
</form>
</div>
</div>
</div>
)
}
}
export default Login

你必须使用withRouter来包装你的组件,那么只有你可以得到this.props.history

而且没有import {browserHistory} from 'react-router-dom'这样的事情

最新更新