简体   繁体   English

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

[英]Nested Routing on exported components with React Router

I was following a CRUD tutorial that used nested Routes like the code below. 我正在关注使用嵌套路由的CRUD教程,如下面的代码。 I tried to omit most of the code that doesn't concern routing. 我试图忽略与路由无关的大多数代码。

After looking up several other tutorials on nested routing I noticed they don't use exported components like I was. 在查找了有关嵌套路由的其他一些教程之后,我发现它们没有像以前那样使用导出的组件。 I also noticed that the tutorial code below exported its components using withRouter. 我还注意到下面的教程代码使用withRouter导出了其组件。

index.js: index.js:

...imports

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

App.js: 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: 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()

The problem I got was that when I tried to access /posts/new or /posts/2 which both should match /posts/:id , I didn't get any match. 我遇到的问题是,当我尝试访问都应该匹配/posts/:id /posts/new/posts/2 ,我没有任何匹配。 The method this.renderPostEditor obviously didn't get called and PostEditor wasn't rendered. 方法this.renderPostEditor显然没有被调用,而PostEditor没有被渲染。

I tried to solve the problem by removing the Route in PostsManager.js and putting in App.js. 我试图通过在PostsManager.js中删除Route并放入App.js来解决问题。 That way I got a match but it didn't render the way I wanted because this.renderPostEditor dependended on PostManager.js 这样我就找到了一个匹配项,但是它没有呈现我想要的方式,因为this.renderPostEditor依赖于PostManager.js

My question is why I didn't get a match inside PostsManager.js but got match in App.js? 我的问题是为什么我在PostsManager.js中没有找到匹配项,但在App.js中得到了匹配项?

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

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

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