React路由同时呈现两个URL。

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

React routing renders two urls at the same time

问题

I have a simple routing that looks like this:

<Switch>
  <div className="privateContent">
    <Route exact path="/games/new">
      <PrivateRoute isLogged={loggedIn}>
        <CreateGame />
      </PrivateRoute>
    </Route>
    <Route exact path="/games/:id">
      <PrivateRoute isLogged={loggedIn}>
        <ShowGame />
      </PrivateRoute>
    </Route>
  </div>
</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:

&lt;Switch&gt;
  &lt;div className=&quot;privateContent&quot;&gt;
    &lt;Route exact path=&quot;/games/new&quot;&gt;
      &lt;PrivateRoute isLogged={loggedIn}&gt;
        &lt;CreateGame /&gt;
          &lt;/PrivateRoute&gt;
    &lt;/Route&gt;
    &lt;Route exact path=&quot;/games/:id&quot;&gt;
      &lt;PrivateRoute isLogged={loggedIn}&gt;
        &lt;ShowGame /&gt;
      &lt;/PrivateRoute&gt;
    &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:

确定