Linguijs: React App Renders Blane Page после реализации динамической активации локали с помощью React-RouterJavascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Linguijs: React App Renders Blane Page после реализации динамической активации локали с помощью React-Router

Сообщение Anonymous »

Я внедряю интернационализацию в своем приложении React (VITE) с использованием Linguijs и React-Router-Dom. Я настроил динамическую загрузку для языковых каталогов на основе параметра URL (/:language/your-route).
Когда я перейду к локализованному URL (например,/en/dashboard или/es/dashboard), страница появляется пустой. В консоли браузера нет ошибок, и нет ошибок на моем бэкэнд -сервере. < /P>

Код: Выделить всё

// App.tsx
import React, { useEffect, useState } from 'react';
import { Routes, Route, useParams, useLocation, Navigate, Outlet } from 'react-router-dom';
import { i18n } from "@lingui/core";
import { I18nProvider, useLingui } from "@lingui/react";

export const supportedLocales = ['en', 'es'];
export const defaultLocale = 'en';

import { Dashboard } from './pages/Dashboard';
import { FamilyHub } from './pages/FamilyHub';
import Editor from './components/ui/Editor/Editor';
import { LoadScript } from '@react-google-maps/api';
import { AuthProvider } from './hooks/useAuth';

export async function dynamicActivate(localeToActivate: string): Promise {
let effectiveLocale = localeToActivate;
let catalogMessages;

if (!supportedLocales.includes(effectiveLocale)) {
console.warn(`LinguiJS: Requested locale "${effectiveLocale}" is not supported.  Falling back to "${defaultLocale}".`);
effectiveLocale = defaultLocale;
}

if (i18n.locale === effectiveLocale && i18n.messages[effectiveLocale]) {
console.log(`LinguiJS: Locale "${effectiveLocale}" is already active and messages are loaded.`);
return effectiveLocale;
}
if (i18n.messages[effectiveLocale] && i18n.locale !== effectiveLocale) {
i18n.activate(effectiveLocale);
console.log(`LinguiJS: Activated pre-loaded locale: "${effectiveLocale}"`);
return effectiveLocale;
}

console.log(`LinguiJS: Attempting to load messages for locale: "${effectiveLocale}"`);
try {
const module = await import(`../locale/${effectiveLocale}/messages.js`);
catalogMessages = module.messages;
} catch (e) {
console.error(`LinguiJS: Failed to load messages for locale: "${effectiveLocale}"`, e);
if (effectiveLocale !== defaultLocale) {
console.warn(`LinguiJS: Attempting to load fallback locale: "${defaultLocale}"`);
try {
const fallbackModule = await import(`../locale/${defaultLocale}/messages.js`);
catalogMessages = fallbackModule.messages;
effectiveLocale = defaultLocale;
} catch (fallbackError) {
console.error(`LinguiJS: Failed to load fallback messages for locale: "${defaultLocale}"`, fallbackError);
throw fallbackError;
}
} else {
throw e;
}
}

if (catalogMessages) {
i18n.load(effectiveLocale, catalogMessages);
i18n.activate(effectiveLocale);
console.log(`LinguiJS: Dynamically loaded and activated locale: "${effectiveLocale}"`);
return effectiveLocale;
} else {
const errorMsg = `LinguiJS: No messages found for locale ${effectiveLocale} after attempting load.`;
console.error(errorMsg);
throw new Error(errorMsg);
}
}

const ActivateLanguage: React.FC = ({ children }) => {
const { language: langFromParams } = useParams();
const location = useLocation(); // Re-trigger effect on any navigation
const [activationState, setActivationState] = useState('pending');

const { i18n: i18nContext } = useLingui();

useEffect(() => {
let isMounted = true;
const targetLocale = (langFromParams && supportedLocales.includes(langFromParams))
? langFromParams
: defaultLocale;

console.log(`[ActivateLanguage Effect] Target: ${targetLocale}, Current Context Locale: ${i18nContext.locale}, Param: ${langFromParams}`);

if (i18nContext.locale === targetLocale && i18nContext.messages[targetLocale]) {
console.log(`[ActivateLanguage Effect] Locale ${targetLocale} already active and loaded in context.`);
if (isMounted) {
setActivationState('activated');
}
return;
}

if (isMounted) {
setActivationState('activating');
setCurrentDisplayLocale(targetLocale);
}

dynamicActivate(targetLocale)
.then((activatedLocale) => {
if (isMounted) {
console.log(`[ActivateLanguage Effect] Dynamic activation successful for "${activatedLocale}".  Global i18n.locale is now: ${i18n.locale}`);
setActivationState('activated');
}
})
.catch((error) => {
if (isMounted) {
console.error("[ActivateLanguage Effect] dynamicActivate failed.", error);
setActivationState('failed');
}
});

return () => {
isMounted = false;
};
}, [langFromParams, location.pathname, i18nContext.locale]);

const [currentDisplayLocale, setCurrentDisplayLocale] = useState(defaultLocale);
useEffect(() => {
setCurrentDisplayLocale((langFromParams && supportedLocales.includes(langFromParams)) ? langFromParams : defaultLocale);
}, [langFromParams]);

if (activationState === 'pending' || activationState === 'activating') {
return Loading translations for {currentDisplayLocale}...;
}

if (activationState === 'failed') {
return Error loading translations. Please check console and refresh.;
}

if (!i18nContext.locale || !i18nContext.messages[i18nContext.locale]) {
console.error("ActivateLanguage Render: Critical - Context i18n.locale not set or messages not loaded despite 'activated' state. Current context locale:", i18nContext.locale);
return Language initialization incomplete after loading. Please refresh.;
}

console.log(`[ActivateLanguage Render] Rendering children for locale: ${i18nContext.locale}`);
return {children};
};

const NavigateToLocalizedHub = () => {
const { hubId } = useParams();
return ;
};

function App() {
return (

 {/* Provide the global i18n instance */}





);
}

export default App;
  • Я положил консоль.log (".."); операторы в самом верху моего App.tsx функция и в верхней части моего ActivateLanguage Function. к подходу Dynamic import () в DynamicActivate


Подробнее здесь: https://stackoverflow.com/questions/796 ... le-activat
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Laravel Blane Page
    Anonymous » » в форуме Php
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • React Router делает неправильный компонент для внуков. @React-router/dev
    Anonymous » » в форуме Javascript
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Handleauth-это не функция с @auth0 / nextjs-auth0 v4.x в next.js app Router / Page.
    Anonymous » » в форуме Javascript
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous
  • Laravel Blade: как получить доступ к переводам строк локали, отличной от текущей локали?
    Anonymous » » в форуме Php
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Экраны на мгновение перекрываются при использовании router.push() из Expo-Router
    Anonymous » » в форуме Javascript
    0 Ответы
    49 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»