代码之家  ›  专栏  ›  技术社区  ›  Evanss

使交换机组件与React路由器尊重URL片段?

  •  1
  • Evanss  · 技术社区  · 6 年前

    这很管用:

    return (
          <div>
            <div>
              <Link to="/one">One</Link>
              <Link to="/two">Two</Link>
            </div>
            <Switch>
              <Route exact path="/one" component={One} />
              <Route exact path="/two" component={Two} />
              <Route component={Three} />
            </Switch>
          </div>
        );
    

    但是,这始终会呈现组件3:

    return (
          <div>
            <div>
              <Link to="/#one">One</Link>
              <Link to="/#two">Two</Link>
            </div>
            <Switch>
              <Route exact path="/#one" component={One} />
              <Route exact path="/#two" component={Two} />
              <Route component={Three} />
            </Switch>
          </div>
        );
    

    https://reacttraining.com/react-router/web/api/HashRouter

    1 回复  |  直到 6 年前
        1
  •  0
  •   zsgomori    6 年前

    组成部分

    你说得对,你应该用 哈希路由器 包裹。基于 documentation ,在您的情况下,适当的配置应该与此类似:

    import { HashRouter } from 'react-router-dom';
    
    <HashRouter basename="/" hashType="noslash">
       <App />
    </HashRouter>
    

    因此根路径更改为 .

    <div>
       <div>
          // http://localhost:3000/#one
          <Link to="/#one">One</Link> // This can be either /one or /#one
          <Link to="/#two">Two</Link>
       </div>
       <Switch>
          <Route exact path="/one" component={One} />
          <Route exact path="/two" component={Two} />
          <Route component={Three} />
       </Switch>
    </div>
    

    不幸的是 路径 道具应该和以前一样。

    文档还包含路由器在这种情况下如何创建href链接的示例。