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

旧城冷巷雨未停 提交于 2019-12-06 03:57:46

问题


I have been trying to resolve this all day and finally i come to you all.

The task is simple, I need to set language type in the URL, so it looks something like this: domain.com/{langVar}/other/paths

And be able to change it by clicking/selecting language in my apps header or any other component.

Important: the language variable should always remain in the URL.

I am using "react-router": "^2.7.0", "react": "^15.3.1".

This is how my router config looks like:

export default (
  <Router history={browserHistory}>
    <Route path="/:lang" component={MainApp}>
      <IndexRoute component={Home} />
      <Route component={OtherPage} />
    </Route>
    <Route path='*' component={NotFound} />
  </Router>
);

I hope this makes, sense if not i will update my question. But to me this seems a pretty normal use case of sites URL.

Thank you


回答1:


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.




回答2:


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"



来源:https://stackoverflow.com/questions/39706654/how-to-set-and-handle-language-in-react-router-from

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