【问题标题】:Redirect back to default language i18n重定向回默认语言 i18n
【发布时间】:2021-10-07 04:41:35
【问题描述】:

如何在 i18n 中设置默认语言?问题是当用户在路径中插入不存在的语言时,页面正在消失。定义的语言是 => en, es, ar。我想将默认语言设置为“EN”,当用户在路径中插入例如“ru”时,用户会重定向回英语。

这是 i18n.js 的代码

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

const languages = ["en", "es", "ar"]
const options = {
    loadPath: "./public/locales/{{lng}}/{{translation}}.json",
}

i18n
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        fallbackLng: "en",
        debug: true,
        // lng: "en",
        whitelist: ["en", "es", "ar"],
        keySeparator: false,
        checkWhitelist: true,
        detection: {
            order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'],  
            lookupFromPathIndex: 0,
            caches: ['cookie'],
            checkWhitelist: true,
        },  
    });
export default i18n;

请注意,此处无法定义 LNG。当我使用 lng 时,翻译不起作用。

文件:Route.js

export const baseUrl = () => {
    return (
        i18n.language === 'en' ? '' : '/' + i18n.language
    )
};

const Router = () => {
    const baseRouteUrl = "/:locale(es|en|ar)?";
    return (
        <Switch>
            <Route exact path="/" component={Options} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/register" component={Register} />

            <PrivateRoute exact path={baseRouteUrl + "/dashboard"}
                    render={(props) => {
                        return (
                            <MainLayout>
                                <DashboardPage />
                            </MainLayout>
                        )
                    }}
                />

文件:Menu.jsx

<Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
     <Menu.Item key="1" active icon={<HomeOutlined />}>
      {
           <Link to={baseUrl() + "/dashboard"}>
               {t("DASHBOARD")}
           </Link>
       }
     </Menu.Item>

【问题讨论】:

    标签: reactjs routes i18next


    【解决方案1】:

    您可以在所有路由的末尾写一个Route 正则表达式路径以捕获所有并重定向。

    <Route
      path="/:lang([A-Za-z]{2})?/:rest*"
      render={props => {
        // availabeLanguages is an array of language codes
        if (!availableLanguages.includes(props.match.params.lang)) {
          // depending on your configuration you may need 
          // to set the language to your default language before return
          return (<Redirect to={`/${props.match.params.rest}`}/>);
        }
      }}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 2014-11-27
      • 1970-01-01
      相关资源
      最近更新 更多