【问题标题】:Convert react-router to v4: Redirect all routes to include lang将 react-router 转换为 v4:重定向所有路由以包含 lang
【发布时间】:2019-05-16 20:11:39
【问题描述】:

我们已经本地化了我们的应用程序,现在我需要在所有路由中包含语言,我遇到了可以做我想做但在 react-router v4 中做同样事情的代码

这是我引用的代码 How to set and handle language in react-router from?

这是我正在使用的示例代码,以便在将其集成到我们的应用之前使其正常工作:

// add lang to url if it's not present
function langRedirect(props) {
  console.log({ props });
  const defaultLang = 'en';
  const redirectPath = `/${defaultLang}${props.history.location.pathname}`;
  console.log(redirectPath);
  props.history.replace({ pathname: redirectPath, });
}

....

<Switch>
  <Route path="/:lang/" render={() => <h1>testing... does nothing</h1>}>
    <Route path="/:lang/test" render={() => <h2>Test</h2>} />
    <Route path="/:lang/test2" render={() => <h2>Test2</h2>} />
  </Route>
  <Route path="*" render={langRedirect} />
</Switch>

这里发生的情况是,如果我转到/test 之类的路由,即使末尾没有 /,交换机仍将捕获 /:lang/ 路由,这会阻止使用langRedirect 进行路由。似乎在 v4 中有不同的行为。

【问题讨论】:

    标签: reactjs react-router react-router-v4 react-router-dom


    【解决方案1】:

    好吧,在花了几个小时之后,我碰巧在发布问题后就弄清楚了......

    我必须像&lt;Route exact path="/:lang/*" render={() =&gt; &lt;h1&gt;Test&lt;/h1&gt;}&gt;那样在路由中添加一个*

    这是工作代码:

    // add lang to url if it's not present
    function langRedirect(props) {
      console.log({ props });
      const defaultLang = 'en';
      const redirectPath = `/${defaultLang}${props.history.location.pathname}`;
      console.log(redirectPath);
      props.history.replace({
        pathname: redirectPath,
      });
    }
    

    ...

    const TestingRoutes = () => {
      return (
        <Switch>
          <Route exact path="/:lang/*" render={() => <h1>Test</h1>}>
            <Route path="/:lang/test" render={() => <h2>Test</h2>} />
            <Route path="/:lang/test2" render={() => <h2>Test2</h2>} />
          </Route>
          <Route path="*" render={langRedirect} />
        </Switch>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2018-06-20
      • 2018-03-18
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多