简体   繁体   English

如何在 react-admin 中从 URL 中的路径获取和管理语言

[英]How to get and manage language from the path in URL in react-admin

react-admin is multilingual, however, you can select and set language in redux store and it is not red from the URL path, there is a premium feature in react-admin that allow user to set language in local storage and make it somehow permanent but sometimes you need to specify language in the URL so that the user is not forced to select a language when they enters the website like below: react-admin 是多语言的,但是,您可以 select 并在 redux 存储中设置语言,并且它不是来自 URL 路径的高级功能,并且在本地存储中以某种方式允许永久用户设置语言但有时您需要在 URL 中指定语言,以便用户在进入如下网站时不会被迫使用 select 语言:

www.testteeetweb.com/fa/posts 

Is there any way to achieve it in react-admin?有没有办法在 react-admin 中实现它?

No, there is no such feature in react-admin.不,react-admin 中没有这样的功能。

You can achieve it outside of your react-admin app, though.不过,您可以在 react-admin 应用程序之外实现它。 Use the history package, and listen to location changes.使用history package,并监听位置变化。 Parse the location to see if the language part of the URL is different, then update the language in a local state.解析位置,看看 URL 的语言部分是否不同,然后在本地 state 中更新语言。 Use that state in the i18nProvider default Language.在 i18nProvider 默认语言中使用 state。

Something like:就像是:

import React, { useState, useEffect } from 'react';
import { Admin } from 'react-admin';
import history from 'history';
import polyglotI18nProvider from 'ra-i18n-polyglot';

const MyComponent= () => {
   const [language, setLanguage] = useState();
   const [i18nProvider, setI18nProvider] = useState();

   useEffect(() => {
        // see https://github.com/ReactTraining/history/blob/master/docs/api-reference.md#history.listen
        return history.listen(({ action, location }) => {
            const newLanguage = extractLanguageFromLocation(location.pathname);
            if (newLanguage !== language) {
                setLanguage(newLanguage)
            }
        })
    }, []);

    useEffect(() => {
        setI18nProvider(polyglotI18nProvider(locale => 
            locale === 'fr' ? frenchMessages : englishMessages,
            language
        ));
    }, [language])

    return (
        <Admin i18nProvider={i18nProvider}>
            // ...
        </Admin>
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM