【问题标题】:Nested Routing on exported components with React Router使用 React Router 对导出的组件进行嵌套路由
【发布时间】:2019-03-05 09:38:51
【问题描述】:

我正在关注一个使用嵌套路由的 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 中得到匹配?

【问题讨论】:

    标签: javascript reactjs react-router-dom


    【解决方案1】:

    尝试从 &lt;Route ... /&gt; 定义中删除 exact 属性。

    【讨论】:

    • 如果您将render={this.renderPostEditor} 替换为render={() =&gt; &lt;span&gt;foo&lt;/span&gt;} 之类的简单名称,还是不行?
    • 仍然不匹配。
    • 我从 App.js 中的 &lt;Route exact path="/posts" component={PostsManager} /&gt; 中取出了 exact 属性,而不是 PostsManager.js 并且它起作用了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    相关资源
    最近更新 更多