如何解决React Router的确切属性不起作用
React路由器中exact
属性的用途是,不要对路由进行部分匹配。但是,就我而言,它没有做。
我有两个组成部分Write an article
和View a particular article with id
。我将两者的路线都定义为:
<Route exact path='/article/write' exact component={ArticleOrBlog}/>
<Route exact path='/article/:id' component={ArticleOne}></Route>
这两个路由都具有exact
属性。预期的行为是,当ArticleOrBlog
组件渲染时,ArticleOne
一定不能渲染,反之亦然。
这是问题所在。
当ArticleOne
组件渲染时,则ArticleOrBlog
组件未渲染,但是当ArticleOrBlog
组件渲染时,ArticleOne
组件也在渲染。
ArticleOne
组件正在ArticleOrBlog
组件下方呈现。
这里的行为发生变化
当我定义路线时:
<Route exact path='/write' exact component={ArticleOrBlog}/>
<Route exact path='/article/:id' component={ArticleOne}></Route>
<Route exact path='/write/anything' exact component={ArticleOrBlog}/>
<Route exact path='/article/:id' component={ArticleOne}></Route>
然后正常工作。
解决方法
当ArticleOrBlog组件呈现时,ArticleOne组件为 也渲染
之所以为什么ArticleOne
组件也要渲染,是因为您在路径中有一个动态参数:id
,该参数可以匹配任何内容,包括write
中的/article/write
。
exact
道具不会阻止反应路由器渲染所有匹配的路由,它仅确保仅渲染完全匹配的路由。
因此,当路线为/article/write
时,它将匹配两个确切路径:
-
/article/write
-
/article/:id
所以这两个组件都呈现出来,而不是像您期望的那样呈现一个。
将路由更改为/write
和/article/:id
时,它可以按预期工作,因为现在/article/:id
与/write
完全不同。
解决方案:
使用Switch
组件,以确保仅呈现第一个匹配的路由。
<Switch>
<Route exact path="/article/write" component={ArticleOrBlog} />
<Route exact path="/article/:id" component={ArticleOne} />
</Switch>
这里要记住的一件事是,当使用上述Switch
时,定义Route
组件的顺序很重要。
对于您来说,Route
和路径/article/write
应该先定义 Route
和路径/article/:id
。这是因为如果在/article/:id
之前定义了/article/write
,则由于动态参数:id
,/article/write
将匹配/article/:id
路径,并且由于{{1} },Switch
路径上的组件将永远不会呈现。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。