这是我的路由器实现
<BrowserRouter>
<div>
<Route exact path="/" component={ProfilesIndex} />
<Route exact path="/profiles" component={ProfilesIndex} />
<Route exact path="/profiles/new" component={ProfileEditor} />
<Route exact path="/profiles/:id" component={ProfileEditor} />
</div>
</BrowserRouter>
当我浏览/profiles/new
路径时,它会渲染ProfileEditor组件两次。对于其他所有路线,它工作正常。
有人可以建议如何解决这个问题吗?
我在浏览Router Docs的多个部分后找到了答案。问题是它匹配多条路线
当用户打开/profiles/new
时,它匹配两条路线
因为:id就像一个通配符*,它也匹配new
字,因此两个路由都匹配,因此组件被渲染两次。
解决方案是使用Switch
包装路由,如果您不想匹配多个路由。
<BrowserRouter>
<Switch>
<Route exact path="/" component={ProfilesIndex} />
<Route exact path="/profiles" component={ProfilesIndex} />
<Route exact path="/profiles/new" component={ProfileEditor} />
<Route exact path="/profiles/:id" component={ProfileEditor} />
</Switch>
</BrowserRouter>