作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一整天都在努力解决这个问题,终于找到了大家。
任务很简单,我需要在 URL 中设置语言类型,所以它看起来像这样:domain.com/{langVar}/other/paths
并且能够通过单击/选择我的应用程序标题或任何其他组件中的语言来更改它。
重要提示:语言变量应始终保留在 URL 中。
我正在使用“react-router”:“^2.7.0”,“react”:“^15.3.1”。
这就是我的路由器配置的样子:
export default (
<Router history={browserHistory}>
<Route path="/:lang" component={MainApp}>
<IndexRoute component={Home} />
<Route component={OtherPage} />
</Route>
<Route path='*' component={NotFound} />
</Router>
);
我希望这是有意义的,如果没有,我会更新我的问题。但对我来说,这似乎是网站 URL 的一个非常正常的用例。
谢谢
最佳答案
扩展这个 stack overflow 问题,我添加了一个名为 userRedirect
的函数,当找不到匹配的路由时将触发该函数。注意 - /
中参数 :lang
后面的 <Route path=":lang/" >
非常重要,因为我们的路由 *
会被命中(如上面共享的堆栈溢出链接中所述。
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
。希望这就是您正在寻找的内容。
关于url - 如何在react-router中设置和处理语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39706654/
我是一名优秀的程序员,十分优秀!