【问题标题】:Confusion With React Router与 React 路由器混淆
【发布时间】:2017-06-16 13:30:10
【问题描述】:

我正在尝试在子组件中使用路由器对象,但无法这样做。我的主要目标是在成功登录后更改路线。在反应路由器 v4 中,我不能直接使用历史对象。

我的主要目标是使用this.context.router,所以我可以进行路线转换。

这是我的应用程序代码(我删除了大部分代码,只是添加了我认为需要的内容)如果您需要更多信息,请发表评论。

路由器

我对如何将组件添加到路由有疑问。但这是我发现使用布局的唯一方法。因此,如果您对此有任何建议,我将不胜感激。

<Router>
    <Switch>

        <Route path="/login" render={ () => ( <LayoutEmpty {...data} children={ <Login user={this.props.user} /> }  /> ) } />

        <Route exact path="/" render={ () => ( <LayoutApp {...data} children={ <Dashboard user={this.props.user} /> }  /> ) } />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

现在让我们谈谈登录组件。在组件内部没有传递上下文对象。

我已经添加了这样的 contextTypes

Login.contextTypes = {
  router: PropTypes.object
};

但这只给了我空对象作为常量。未传递路由对象。

(如果您需要登录组件的代码,请告诉我,但我认为我在使用 &lt;Route&gt; 时遇到问题)

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

我最终重构了我的代码并将历史对象向下传递到智能组件(容器)级别。

我的重构路由器看起来像这样

<Router>
    <Switch>

        <Route path="/login" component={Login} />

        <Route exact path="/" component={Dashboard} />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

之后,我将我的 Layout 组件导入到容器(LoginDashboard),并在需要时将历史对象作为道具传递给这些容器。

容器(智能组件)

import React from 'react';
import LayoutApp from '../containers/LayoutApp'

    class Dashboard extends React.Component{
    ...
    render(){   
            return (    
            <LayoutApp history={this.props.history} title="Dashboard">  
             ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多