【问题标题】:react-router-dom v4 Redirect to programaticallyreact-router-dom v4 以编程方式重定向到
【发布时间】: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


【解决方案1】:

您需要指定您希望组件可以访问哪些上下文属性。假设您的 xhr 请求在您的 UserLogin 组件中,您将需要添加以下内容以访问 context.history。

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

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

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);

【讨论】:

  • 我在文档中看到他们使用的是PropTypes,但是当我尝试这样做时,我得到了duplicate declaration of "PropTypes"。您能否提供一个包含构造函数和PropTypes 使用的响应?
  • 我不确定你的意思。谁在使用道具类型?你想在哪里使用它?
  • 发现问题。谢谢你。我也从react 导入了PropTypes,基本上它们被导入了两次,一次来自新的PropTypes 模块,一次来自React。
猜你喜欢
  • 2018-04-04
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2016-07-01
  • 2018-10-23
相关资源
最近更新 更多