reactjs - 将 i18next 实例传递给 I18nextProvider 时出现类型错误

标签 reactjs typescript i18next react-i18next

错误:

Type 'Promise' is missing the following properties from type 'i18n': t, init, loadResources, use, and 32 more.ts(2740) index.d.ts(344, 3): The expected type comes from property 'i18n' which is declared here on type 'IntrinsicAttributes & I18nextProviderProps & { children?: ReactNode; }'

i18n/intex.ts

import { NODE_ENV } from "@/config";
import i18n from "i18next";
import { initReactI18next } from "react-i18next";

export default i18n.use(initReactI18next).init({
  fallbackLng: "en",
  debug: NODE_ENV === "development"
});

providers/app.tsx

import { AuthProvider } from "@/lib/auth";
import { queryClient } from "@/lib/react-query";
import { ReactNode, Suspense } from "react";
import { QueryClientProvider } from "react-query";
import { BrowserRouter as Router } from "react-router-dom";
import { ReactQueryDevtools } from "react-query/devtools";
import { ConfigProvider } from "antd";
import en from "antd/lib/locale/en_US";
import { I18nextProvider } from "react-i18next";
import i18n from "@/i18n";

type AppProviderProps = {
  children: ReactNode;
};

export const AppProvider = ({ children }: AppProviderProps) => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ConfigProvider locale={en}>
        <QueryClientProvider client={queryClient}>
          {import.meta.env.DEV && <ReactQueryDevtools />}
          <AuthProvider>
            <I18nextProvider i18n={i18n}>
              <Router>{children}</Router>
            </I18nextProvider>
          </AuthProvider>
        </QueryClientProvider>
      </ConfigProvider>
    </Suspense>
  );
};

最佳答案

// this returns a promise not an i18n instance
export default i18n.use(initReactI18next).init({
  fallbackLng: "en",
  debug: NODE_ENV === "development"
});

这应该有效:

// don't care for the promise
i18n.use(initReactI18next).init({
  fallbackLng: "en",
  debug: NODE_ENV === "development"
});

// just return the instance you have
export default i18n;

或等待 promise (这仅适用于顶级等待支持):

export default await i18n.use(initReactI18next).init({
  fallbackLng: "en",
  debug: NODE_ENV === "development"
});

关于reactjs - 将 i18next 实例传递给 I18nextProvider 时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71762425/

相关文章:

ios - react native : Could not connect to development server

reactjs - Nextjs 使用 Typescript 时出现 Home 和 GetServerSideProps 类型错误

javascript - React : Best way to update self, 但阻止 child 更新?

用于多语言支持的 Angular 6 CLI 本地化和国际化

javascript - 如何使用变量作为 i18next 的键?

reactjs - 在 React 中获取文档的高度

typescript - Typescript 中的 d3.max(...) 返回一个字符串

typescript - 有没有办法从不同长度的元组的联合中提取带有类型的最后一个元素?

next.js - Zod 基于 Next.js 中事件区域设置的动态错误消息

javascript - i18next - "WebpackError: TypeError: namespaces.forEach is not a function"(钩子(Hook))