【问题标题】:React-router routes with multiple children具有多个子节点的 React-router 路由
【发布时间】:2016-11-11 19:58:29
【问题描述】:

我的一条路线需要两个孩子来完成我想做的事情。

我定义所有路由的主应用页面可能如下所示:

    <Route path="/logs" component={Logs}>
        <Route path="/logs/archive(/**)" component={ArchiveAction}></Route>
        <Route path="/logs/view(/**)" component={LogApp}></Route>
    </Route>

至于 Logs 组件,如果我在 /logs/view/whatever 路由,它将呈现名为 LogApp 的组件,它将是整个页面。

如果它位于 /logs/archive/whatever Logs 的一个子组件上,那么它会发生什么变化。但这部分工作正常。我不能去工作的是/logs/view/whatever。这是我当前的日志组件:

export class Logs extends Component{

    render(){
        var initialLogsPage =(<Grid>
                <Row>

                    <Col lg={4} md={4} sm={4}>
                        <Directories/>
                    </Col>
                    <Col lg={4} md={4} sm={4}>
                        <Archives children={this.props.children}/>
                    </Col>

                </Row>
            </Grid>);
        return(
            <div>
            {initialLogsPage || this.props.children}
            </div>
        );
    }
}

我知道我对 this.props.children 的使用可能是问题所在,因为我正在处理两个问题。有没有办法解决这个问题?

【问题讨论】:

  • 这将始终显示initalLogsPage 渲染。
  • 我知道。我该怎么做才能让它显示 LogApp 组件?
  • 我真的不太了解 React 来提供帮助,但你能尝试交换这些变量吗? {this.props.children || initialLogsPage}
  • 恐怕没有用 :( 不过谢谢!

标签: javascript reactjs react-router react-router-component


【解决方案1】:

只需更改路线:

<Route path="/logs" component={Logs}>
    <Route path="/logs/archive(/**)" component={ArchiveAction}></Route>
</Route>
<Route path="/logs/view(/**)" component={LogApp}></Route>

【讨论】:

  • 这就是我目前拥有的方式。不幸的是,为了在主应用程序组件的导航栏上保持一致性,理想情况下我需要将第二个子路由放在 /logs 内
  • 我能想到的唯一其他方法是检查路线本身。我相信您可以从this.state.location.pathname 访问它。然后你可以检查路由是否从/logs/view开始渲染{this.props.children},否则渲染initialLogsPage
【解决方案2】:

您可以在没有路径的情况下使用Routes:

// Route config
<Route path="/logs" component={Logs}>
  <Route component={Archives}>
    <Route path="/logs/archive(/**)" component={ArchiveAction}></Route>
  </Route>
  <Route path="/logs/view(/**)" component={LogApp}></Route>
</Route>

// components
const Archives = ({ children }) => (
  <Grid>
    <Row>
      <Col lg={4} md={4} sm={4}>
        <Directories/>
      </Col>
      <Col lg={4} md={4} sm={4}>
        <Archives>{children}</Archives>
      </Col>
    </Row>
  </Grid>
);

const Logs = ({ children }) => <div>{children}</div>; // add shared layout here

您还应该考虑应该在/logs 上呈现什么。将Logs 更改为检查props.children,例如&lt;div&gt;{children || &lt;LogIndexComponent /&gt;}&lt;/div&gt;,或者在您的路由配置中包含IndexRoute。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多