我使用的是类似的代码像这样在我的应用程序将用户重定向登录后的代码如下所示:
import React, { Component } from 'react'
import { Redirect } from 'react-router'
export default class LoginForm extends Component {
constructor () {
super();
this.state = {
fireRedirect: false
}
}
submitForm = (e) => {
e.preventDefault()
//if login success
this.setState({ fireRedirect: true })
}
render () {
const { from } = this.props.location.state || '/'
const { fireRedirect } = this.state
return (
<div>
<form onSubmit={this.submitForm}>
<button type="submit">Submit</button>
</form>
{fireRedirect && (
<Redirect to={from || '/home'}/>
)}
</div>
)
}
}
当成功登录被触发时工作正常。但有一种情况,登录用户进入登录页面并应自动重定向到“主页”页面(或任何其他页面)。
如何在不呈现当前组件并且没有(据我所知不鼓励)强制推送到历史记录(例如 in componentWillMount
)的情况下使用重定向组件?