react-router-dom v4以编程方式重定向

时间:2017-05-12 22:40:41

标签: node.js reactjs react-router

我有一个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')部分外,一切都很好。登录后如何重定向用户?通过使用该方法,我在控制台中看到this.context未定义。

Cannot read property 'push' of undefined

1 个答案:

答案 0 :(得分:1)

您需要指定组件有权访问的上下文属性。假设你的xhr请求在你的UserLogin组件中,你需要添加以下内容来访问context.history。

UserLogin.contextTypes = {
    history: React.PropTypes.object,
};

但你不应该使用上下文,而应该使用React Routers withRouter函数,它会将history放在你组件的道具上。

https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class UserLogin extends React.Component { ... }

// can call history with this.props.history in UserLogin now
export default withRouter(UserLogin);
相关问题