【问题标题】:React router exact property is not working反应路由器确切属性不起作用
【发布时间】:2020-12-04 09:59:57
【问题描述】:

exactexactreact router 属性的目的是,不要做路由的部分匹配。但是,就我而言,它没有做。

我有两个组件 Write an articleView 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> 

然后它就可以正常工作了。

【问题讨论】:

标签: reactjs path react-router


【解决方案1】:

当 ArticleOrBlog 组件呈现时,ArticleOne 组件是 也渲染

ArticleOne 组件也呈现的原因是因为您在路由中有一个动态参数 :id 匹配任何内容,包括 /article/write 中的 'write'

exact prop 不会阻止 react 路由器渲染所有匹配的路由;它只确保只有完全匹配的路由被渲染。

所以当路由为/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 路径并且由于Switch,将永远不会呈现/article/write 路径上的组件.

【讨论】:

  • 谢谢,对我很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2015-11-25
  • 2017-02-24
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多