【问题标题】:Redux + React : react router only rendering index routeRedux + React:react router 只渲染索引路由
【发布时间】:2017-06-08 08:23:08
【问题描述】:

我已尝试关注this question 上的答案,但无济于事。 我正在尝试使用反应路由器和嵌套路由来根据路由器的配置呈现不同的布局。 但是带有path="/" 的路由总是会显示,而不管存在的 URL 是什么。 这是我正在使用的路由器。

        <Route component={App}>
            <Route component={LayoutOne}>
                <Route path="/" component={ComponentOne}/>
            </Route>
            <Route component={LayoutTwo}>
                <Route path="category" component={ComponentTwo}/>
            </Route>
        </Route>

这是我用来将调度映射到道具并连接的 App 文件。

function mapStateToProps(state, ownProps){
    return{
        exampleProp: state.exampleProp,
    };
}

function mapDispatchToProps(dispatch){
    return bindActionCreators(actionCreators, dispatch);
}


const App = connect(mapStateToProps, mapDispatchToProps)(MainLayout);

export default App;

这是上面看到的主要布局MainLayout

export default class MainLayout extends Component {
    render(){
       <div className="main-layout">
            {this.props.children}
       </div>
    }
}

LayoutOne 和 LayoutTwo(为简洁起见已省略)是简单的类 rapper,如下所示。

导出默认类 LayoutOne 扩展组件{ 使成为(){ 返回( {this.props.children} ) } }

这里的 ComponentOne 和 ComponentTwo 分别只是简单的组件。

我的问题是,无论存在什么 URL,只有 ComponentOne 会呈现。 如何解决此问题,以便可以使用如上所示的嵌套路由? 您的帮助将不胜感激。 如果您需要任何其他信息,请询问,我会尽力使用所需信息更新问题。 谢谢。

【问题讨论】:

  • 只是好奇 - 使用 /category 代替 category 有效吗?

标签: reactjs redux react-router react-redux children


【解决方案1】:

您遇到的问题是索引路由,即'/',在您的路由树中首先匹配,并且因为它匹配任何路由,所以它是每次都被渲染的路由。

您可以通过将带有path="category"Route 移到带有path="/" 的上方来解决此问题。这样,首先检查更详细的路线选项。为了清楚起见,我还建议将 path="category" 更改为 path="/category",因为它们都是根级路由。

【讨论】:

    【解决方案2】:

    将您的路线更改为如下所示应该可以解决您的问题

    <Route component={App} path="/">
        <Route component={LayoutOne} path="">
            <Route component={ComponentOne}/>
        </Route>
        <Route component={LayoutTwo} path="category">
            <Route component={ComponentTwo}/>
        </Route>
    </Route>
    

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2020-09-12
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 2016-02-22
      • 2018-10-18
      相关资源
      最近更新 更多