sac*_*024 3 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>
Run Code Online (Sandbox Code Playgroud)
当我浏览/profiles/new路径时,它两次渲染ProfileEditor组件。对于其他所有路线,它都可以正常工作。
有人可以建议如何解决此问题吗?
对于从 v6+ 来到这里的任何人
exactprop 不再存在,如果未附加通配符,则默认路径是准确的*
然而我仍然得到了双重渲染。我运行了一个产品构建并进行了检查,双渲染消失了,所以可能没有什么可担心的 - 有时钩子在开发模式下运行两次(我猜这就是内部发生的情况)
浏览路由器文档中的多个部分后,我找到了答案。问题是它匹配多条路线
当用户打开时,/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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
844 次 |
| 最近记录: |