和vue路由不同,react路由提供了一个exact
属性,当地址栏中的地址完全匹配此路由时,才会渲染这个路由对应的组件。
应用实例: 这是我在坑里的场景
当编辑和新建共用一个页面文件时,由于写的路由前半部分相同,所以会导致路由匹配到两次,进而会导致页面中元素都渲染了两次,完完全全地两次。
入坑代码 反例:
<Route path="/topic/:id" component={topic}></Route>
<Route path="/topic" component={topic}></Route>
跳出坑的代码 正例:
<Route path="/topic/:id" component={topic}></Route>
<Route path="/topic" exact component={topic}></Route>
或者更优雅地写法:
<Route path="/topic/edit/:id" component={topic}></Route>
<Route path="/topic/create" component={topic}></Route>