【问题标题】:React Router Nested Routes?反应路由器嵌套路由?
【发布时间】:2019-02-18 20:24:55
【问题描述】:

所以我有一个 React 应用程序,它的主要路线是

/
/projects
/gallery
/about

我想要一个看起来像这样的嵌套路由

/projects/skout

我不知道为什么,但是这条路线没有从相应的组件文件中呈现正确的 HTML。它只是空的。

应用组件

class App extends Component {

  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  render() {

    let routes = (
      <Switch>
        <Route exact path="/projects/skout" Component={Skout} />
        <Route exact path="/about" component={About} />
        <Route exact path="/projects" component={Projects} />
        <Route exact path="/gallery" component={Gallery} />
        <Route exact path="/" component={Home} />
        <Redirect exact to="/" />
      </Switch>
    )

    return (
      <BrowserRouter>
        <div className="App" styleName="main-wrapper">
          <Layout>
              {routes}
          </Layout>
        </div>
      </BrowserRouter>

    );
  }
}

export default CSSModules(App, styles);

Skout 组件

import React from 'react';

const skout = (props) => (
    <div>
        <span className="container">
            <div className="row">
                <h1>
                    Gallery
                </h1>
            </div>
            <span className="container">
                <p>
                    Storage for Photos, Ideas, and Thoughts
                </p>
            </span>
        </span>
    </div>
)

export default skout;

我是否必须在/projects 组件中放置一个路由?

【问题讨论】:

标签: html reactjs react-router


【解决方案1】:

您需要在Layout 内渲染匹配的路由组件,因为它们是嵌套路由:

  export const Layout = ({ children }) => (
     <React.Fragment>
            {children}
     </React.Fragment>
   )

但是在 react router v4 中,嵌套路由需要单独渲染。您需要将路由放入 Layout 组件中。

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2017-07-23
    • 2017-08-06
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多