如何在React Router中设置和处理语言? [英] How to set and handle language in react-router from?
问题描述
我整天都在努力解决这个问题,最后我来到了大家面前.
I have been trying to resolve this all day and finally i come to you all.
任务很简单,我需要在URL中设置语言类型,因此看起来像这样:domain.com/{langVar}/other/paths
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.
重要:语言变量应始终保留在URL中.
Important: the language variable should always remain in the URL.
我正在使用反应路由器":"^ 2.7.0",反应":"^ 15.3.1".
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>
);
我希望这有意义,如果没有的话,我会更新我的问题.但是对我来说,这似乎是网站URL的非常正常的使用案例.
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.
谢谢
推荐答案
扩展此堆栈溢出问题,我添加了一个名为userRedirect
的函数,该函数将在找不到匹配的路由时触发.注意-在<Route path=":lang/" >
中的参数:lang
之后的/
非常重要,因为我们的路由*
被命中(如上面共享的堆栈溢出链接所述.
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>
如果您导航到URL <domain>/about/show
,它将被重定向到<domain>/en-gb/about/show
.希望这就是您想要的.
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.
这篇关于如何在React Router中设置和处理语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!