反应路由器确切属性不起作用

6 path reactjs react-router

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

我有两个组件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> 
Run Code Online (Sandbox Code Playgroud)

两条路线都有exact财产。预期的行为是,当ArticleOrBlog组件呈现时ArticleOne必须不,反之亦然。

这里的问题是一致的。

当ArticleOne组件呈现时,ArticleOrBlog组件不呈现,但当ArticleOrBlog组件呈现时,组件ArticleOne也在呈现。 ArticleOne组件正在组件下方呈现ArticleOrBlog。

这里行为改变

当我定义路由时:

<Route exact path='/write' exact component={ArticleOrBlog}/>   
<Route exact  path='/article/:id'  component={ArticleOne}></Route> 
Run Code Online (Sandbox Code Playgroud)
<Route exact path='/write/anything' exact component={ArticleOrBlog}/>   
<Route exact  path='/article/:id'  component={ArticleOne}></Route> 
Run Code Online (Sandbox Code Playgroud)

然后它工作正常。

You*_*saf 7

当 ArticleOrBlog 组件呈现时,ArticleOne 组件也在呈现

之所以ArticleOne组件也呈现是因为你有一个动态PARAM:id其中匹配任何东西,包括路线write中/article/write。

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

因此,当路由为 时/article/write,它匹配两条精确路径:

  • /article/write
  • /article/:id

所以两个组件都被渲染,而不是像你预期的那样只渲染一个。

当您将路由更改为/writeand 时/article/:id,它会按预期工作,因为 now/article/:id与/write.

解决方案:

使用Switch将确保仅呈现第一个匹配的路由的组件。

<Switch>
   <Route exact path="/article/write" component={ArticleOrBlog} />
   <Route exact path="/article/:id" component={ArticleOne} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

这里要记住的一件事是,当使用Switch如上所示时,Route定义组件的顺序很重要。

在你的情况下,Routewith path/article/write 应该在 Routewith path之前定义/article/:id。这是因为如果/article/:id在之前定义/article/write,那么由于动态参数:id,/article/write将匹配/article/:id路径,并且因为Switch,/article/write路径中的组件将永远不会被呈现。