代码之家  ›  专栏  ›  技术社区  ›  Sachin Jain

反应路由器v4渲染组件两次

  •  1
  • Sachin Jain  · 技术社区  · 7 年前

    这是我的路由器实现

    <BrowserRouter>
      <div>
        <Route exact path="/" component={ProfilesIndex} />
        <Route exact path="/profiles" component={ProfilesIndex} />
        <Route exact path="/profiles/new" component={ProfileEditor} />
        <Route exact path="/profiles/:id" component={ProfileEditor} />
      </div>
    </BrowserRouter>
    

    当我浏览到 /profiles/new

    有人能建议如何解决这个问题吗?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Sachin Jain    7 年前

    我在浏览了多个章节后找到了答案 Router Docs . 问题是它匹配了多条路线

    /profiles/new 它匹配两条路线

    因为:id就像一个通配符*而且它也匹配 new 所以两条路径都匹配,因此组件被渲染两次。

    Switch 如果不想匹配多个路由。

    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={ProfilesIndex} />
        <Route exact path="/profiles" component={ProfilesIndex} />
        <Route exact path="/profiles/new" component={ProfileEditor} />
        <Route exact path="/profiles/:id" component={ProfileEditor} />
      </Switch>
    </BrowserRouter>