【发布时间】:2017-05-12 22:40:41
【问题描述】:
我有一个UserLogin 组件,它将发送一个请求,并且在得到响应后我想重定向到AfterLogin 组件。
if (xhr.status === 200) {
// success
this.context.history.push('/dashboard')
}
经过大量搜索,我的 react-router-dom v4 路由器看起来像这样:
import { BrowserRouter as Router, Route, Switch,Redirect} from 'react-router-dom'
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
<Router forceRefresh={false} history={history}>
<div>
<Switch>
<Route exact path="/" render={() => (
Auth.isUserAuthenticated() ? (
<DashboardPage/>
) : (
<LoginPage/>
)
)}/>
<Route path="/dashboard" render={() => (
Auth.isUserAuthenticated() ? (
<DashboardPage/>
) : (
<Redirect to="/login"/>
)
)}/>
<Route path="/login" render={() => (
Auth.isUserAuthenticated() ? (
<Redirect to="/dashboard"/>
) : (
<LoginPage/>
)
)}/>
<Route path="*" component={Error}/>
</Switch>
</div>
</Router>
除了this.context.history.push('/dashboard')part 之外,一切都运行良好。登录后如何重定向用户?通过使用该方法,我在控制台中看到 this.context 未定义。
Cannot read property 'push' of undefined
【问题讨论】:
-
您应该使用道具而不是上下文,例如
this.props.history.push('/dashboard')。你现在在哪里打电话给this.context...? -
在 UserLogin 组件中,用户提交表单并从服务器返回 ok 后。
标签: node.js reactjs react-router