【发布时间】: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