reactjs - React Router v4 渲染组件两次
问题描述
这是我的路由器实现
<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
因为 :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>
推荐阅读
- activemq - ActiveMQ 配置:BrokerXMLConfig activemq.xml - 未找到相对路径文件
- r - 如何在 igraph 中保留网络的一般形状?
- android - 如何读取所有子节点值并在firebase android中使用它们
- java - Java 中列表 String 和 String[] 列表,或 T 列表和 T[] 列表的通用方法
- php - 在运行时禁用 XDebug
- php - Mongo Db PHP 根据特定字段查找行数
- python - Python if 函数以无效语法回复
- java - 如何反/序列化具有动态类型属性的实例
- java - Thymeleaf 无法在单元测试的临时目录中找到片段
- java - o(1) 或 o(n) 的复杂度是多少?