React路由同时呈现两个URL。

huangapple go评论91阅读模式
英文:

React routing renders two urls at the same time

问题

I have a simple routing that looks like this:

  1. <Switch>
  2. <div className="privateContent">
  3. <Route exact path="/games/new">
  4. <PrivateRoute isLogged={loggedIn}>
  5. <CreateGame />
  6. </PrivateRoute>
  7. </Route>
  8. <Route exact path="/games/:id">
  9. <PrivateRoute isLogged={loggedIn}>
  10. <ShowGame />
  11. </PrivateRoute>
  12. </Route>
  13. </div>
  14. </Switch>

My react routing version is 5.2.0, and according to what I have read about it, when using Switch, it should render the FIRST path it matches. HOWEVER, when I try to reach games/new, BOTH of <ShowGame /> and <CreateGame /> get rendered.

How to fix this?

英文:

i have a simple routing that looks like this:

  1. &lt;Switch&gt;
  2. &lt;div className=&quot;privateContent&quot;&gt;
  3. &lt;Route exact path=&quot;/games/new&quot;&gt;
  4. &lt;PrivateRoute isLogged={loggedIn}&gt;
  5. &lt;CreateGame /&gt;
  6. &lt;/PrivateRoute&gt;
  7. &lt;/Route&gt;
  8. &lt;Route exact path=&quot;/games/:id&quot;&gt;
  9. &lt;PrivateRoute isLogged={loggedIn}&gt;
  10. &lt;ShowGame /&gt;
  11. &lt;/PrivateRoute&gt;
  12. &lt;/Route&gt;

my react routing version is 5.2.0 and according to what i have read about it, when using Switch it should render the FIRST path it matches, HOWEVER, when i try to reach games/new BOTH of &lt;ShowGame /&gt; and &lt;CreateGame /&gt; get rendered

How to fix this?

答案1

得分: 1

问题出在所有路由之上的 <div className="privateContent"> - 当所有的 都是 的直接子级时,它的功能正常。

将这个 <div> 放在 <Switch> 之上,它应该能正常工作。

英文:

The problem is the &lt;div className=&quot;privateContent&quot;&gt; above all routes - &lt;Switch&gt; works as expected when all &lt;Route&gt;s are direct children of &lt;Switch&gt;.

Put this div above &lt;Switch&gt; and it should work.

huangapple
  • 本文由 发表于 2023年5月21日 17:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定