簡體   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