gpt4 book ai didi

url - 如何在react-router中设置和处理语言?

转载 作者:行者123 更新时间:2023-12-03 13:27:03 27 4
gpt4 key购买 nike

我一整天都在努力解决这个问题,终于找到了大家。

任务很简单,我需要在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com