How to set and handle language in react-router from?

独自空忆成欢 提交于 2019-12-04 07:35:56

Extending this stack overflow question, I added a function called userRedirect which will be triggered when the matching route isn't found. Note - the / following argument :lang in <Route path=":lang/" > is very important due to which our route * gets hit (as explained in the stack overflow link shared above.

import React from 'react';
import { Route } from 'react-router';
import { App, About } from './containers';

function userRedirect(nextState, replace) {
  var defaultLanguage = 'en-gb';
  var redirectPath = defaultLanguage + nextState.location.pathname
  replace({
    pathname: redirectPath,
  })
};

<Route path="/" component={App}>
  <Route path=":lang/" >
    <Route path="about">
      <Route path="show" component={About}/>
    </Route>
  </Route>
  <Route path="*" onEnter={userRedirect} />
</Route>

If you navigate to the url <domain>/about/show, it will be redirected to <domain>/en-gb/about/show. Hope this is what you were looking for.

this answer is almost nice

 function userRedirect(nextState, replace) {
  var defaultLanguage = 'en-gb';
  var redirectPath = defaultLanguage + nextState.location.pathname
  replace({
    pathname: redirectPath,
  })
};

<Route path="/" component={App}>
  <Route path=":lang/" >
    <Route path="about">
      <Route path="show" component={About}/>
    </Route>
  </Route>
  <Route path="*" onEnter={userRedirect} />
</Route>

but for me it wasnt good. Since first of all it should be

    var redirectPath = defaultLanguage + '/' + nextState.location.pathname

links i think should be added not just like "/link-to-page" but "en/link-to-page" because function "userRedirect" is always fired. Every time you click the link. And because of this your url is to become "...en/en/en/en/link-to-page"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!