繁体   English   中英

使用React Router在导出的组件上进行嵌套路由

[英]Nested Routing on exported components with React Router

我正在关注使用嵌套路由的CRUD教程,如下面的代码。 我试图忽略与路由无关的大多数代码。

在查找了有关嵌套路由的其他一些教程之后,我发现它们没有像以前那样使用导出的组件。 我还注意到下面的教程代码使用withRouter导出了其组件。

index.js:

...imports

ReactDOM.render(
    <BrowserRouter>
       <App />
    </BrowserRouter>,
    document.getElementById('root'),
);

App.js:

const App = ({ classes }) => (
     <CssBaseline />
     <AppHeader />
     <main className={classes.main}>
       <Home />
       <Route exact path="/" component={Home} />
       <Route exact path="/posts" component={PostManager} /> //This renders a list of posts
     </main>
   </Fragment>

PostsManager.js:

...imports

...constructor and other functions (this.savePost)

  renderPostEditor = ({ match: { params: { id } } }) => {
    if (this.state.loading) return null;
    const post = find(this.state.posts, { id: Number(id) });

    if (!post && id !== 'new') return <Redirect to="/posts" />;

    return <PostEditor post={post} onSave={this.savePost} />;
  };

  render() { //component render funciton
        ...
        <Button
          variant="fab"
          color="secondary"
          aria-label="add"
          className={classes.fab}
          component={Link}
          to="/posts/new"
        >
        <Route exact path="/posts/:id" render={this.renderPostEditor} />
  }
 ...exporting component withRouter()

我遇到的问题是,当我尝试访问都应该匹配/posts/:id /posts/new/posts/2 ,我没有任何匹配。 方法this.renderPostEditor显然没有被调用,而PostEditor没有被渲染。

我试图通过在PostsManager.js中删除Route并放入App.js来解决问题。 这样我就找到了一个匹配项,但是它没有呈现我想要的方式,因为this.renderPostEditor依赖于PostManager.js

我的问题是为什么我在PostsManager.js中没有找到匹配项,但在App.js中得到了匹配项?

尝试从<Route ... />定义中删除exact道具。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM