Я внедряю интернационализацию в своем приложении 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
Я внедряю интернационализацию в своем приложении React (VITE) с использованием Linguijs и React-Router-Dom. Я настроил динамическую загрузку для языковых каталогов на основе параметра URL (/:language/your-route). Когда я перейду к локализованному URL (например,/en/dashboard или/es/dashboard), страница появляется пустой. В консоли браузера нет ошибок, и нет ошибок на моем бэкэнд -сервере. < /P> [code]// 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";
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); } }
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'); } });
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}; };
export default App; [/code] [list] [*] Я положил консоль.log (".."); операторы в самом верху моего App.tsx функция и в верхней части моего ActivateLanguage Function. к подходу Dynamic import () в DynamicActivate
Я пытаюсь запустить проект Laravel (php) + vite (vue). На Localhost: 5173 Page.
Когда я запускаю сборку Docker и переднюю часть, я получаю доступ к Localhost, и все, что я получаю, это пустая страница.
Я пытаюсь интегрировать аутентификацию Auth0 в проект next.js с использованием официального пакета @auth0 /nextjs-auth0 (v4.7.0).
Я тщательно следовал как официальной документации, так и нескольким гидам сообщества.
Я попробовал обе эти настройки:...
Я новичок в Laravel. Пожалуйста, рассмешите меня. Я работаю над веб-сайтом, который можно использовать на двух разных языках. У меня есть два файла, en.json и te.json, в resources/lang:
// en.json
language-text : English
Я пытаюсь перемещаться между двумя страницами, используя метод router.push() Expo Router. Мой тип навигатора — стек. Хотя этот метод и перевел меня на новую страницу, между старой и новой страницами происходит кратковременное перекрытие. Кажется,...