next-i18next 常见Bug记录

TypeError: Cannot read property 'wait' of null

此处根本原因为next版本(使用withNamespaces导入命名空间报错)
^5.0.0版本不支持导入_app.js导致i18n注入失败
^6.0.0版本或者以上版本会支持导入_app.js
尝试更新withNamespaces的wait和options并没有效果,相反会导致之后的一系列bug
此处使用next-i18next步骤链接: [next-i18next].
附上react-i18next的链接: [react-i18next].
附上i18next的链接: [i18next].
附上语言转换操作技巧:使用translate-components插件可以通过node命令进行生成对应json文件,然后根据需要进行转换即可

You have not declared a namespacesRequired array on your page-level component

此处在页面级组件不导入namespacesRequired命名空间组或者在static下的locales有未引用的json都会报这个警告

nexti18next FrontWebsite Router Options

此处如果next没有版本限制并且可以使后台支持最好的办法是使用官方文档推荐做法
此方案适用于因后台无法提供支持且无法使用pm2服务器

  1. 更改exportPathMap配置使带有语言前缀的路径可以正常刷新定向
  2. 在next钩子_app.js中render之前去检测当前Router路径得以判断出当前应该changeLanguage哪种语言
  3. 封装next/link next/router以使前端的路由定向正常
以下附上代码方案
/**************************************
    --------------_app.js--------------
**************************************/
import React from 'react'
import App, { Container } from 'next/app'
import { i18n, appWithTranslation } from '../i18n'

class MyApp extends App {
//     static async getInitialProps({ Component, ctx }) {
//       // const language = ctx ? ctx.req.headers['accept-language'] : (navigator.language || navigator.browserLanguage).toLowerCase()
//    let pageProps = {}
//     
//       if (Component.getInitialProps) {
//         pageProps = await Component.getInitialProps(ctx)
//       }
//     
//       return { pageProps }
//     }
  render() {
    const { Component, pageProps } = this.props
    // console.log(this.props)
    const languageUrl = this.props.router.asPath.replace(/\//g, '').substr(0, 2)
    const languages = ['zh', 'th']
    const language = ~languages.indexOf(languageUrl) ? languageUrl : languages[0]
    i18n.changeLanguage(language)
    return (
        <Container>
                <Component {...pageProps} />
        </Container>
    )
    }
}

export default appWithTranslation(MyApp)

/**************************************
    --------------Link---------------
**************************************/
import React from 'react'
import NextLink from 'next/link'
import { i18n } from '../../i18n'

class Link extends React.Component {
    render () {
        const {
            as,
            href,
            children,
            ...props
        } = this.props;
        
        return React.createElement(NextLink, { 
            href: href,
            as: `/${i18n.language}${href}`
        }, children);
    }
}

export default Link

/**************************************
    ------------Router-------------
**************************************/
import NextRouter from 'next/router';
import { i18n } from '../../i18n'
const propertyFields = ['pathname', 'router', 'query', 'asPath', 'components', 'events'];
const coreMethods = ['reload', 'back', 'beforePopState', 'ready', 'prefetch'];
const wrappedMethods = ['push', 'replace'];

const Router = {};
propertyFields.forEach(field => {
Object.defineProperty(Router, field, {
    get() {
    return NextRouter[field];
    }
});
});
coreMethods.forEach(method => {
Router[method] = (...args) => NextRouter[method](...args);
});
wrappedMethods.forEach(method => {
Router[method] = (path, as, options) => {
    return NextRouter[method](path, `/${i18n.language}${path}`, options);
};
});

export default Router;

转载于:https://www.cnblogs.com/universe-cosmo/p/10968942.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React-i18next是一个用于React应用程序的国际化(i18n)库,它帮助开发者轻松地在应用中实现多语言支持。它结合了React和i18next这两个库的优点,让翻译文本变得简单且管理起来更加高效。 以下是使用React-i18next的基本步骤: 1. 安装依赖: ``` npm install react-i18next i18next axios // 如果你想从服务器获取翻译文件 ``` 2. 创建i18n配置: 在项目的`i18n.js`或类似的文件中,设置默认的语言、提供翻译资源(通常是JSON文件)、并初始化i18next: ```javascript import i18n from 'i18next'; import Backend from 'i18next-http-backend'; // 使用axios或其他HTTP backend i18n .use(Backend) // 加载HTTP backend .init({ lng: 'en', // 默认语言 fallbackLng: 'en', // 当语言不可用时的备选语言 resources: { // 翻译资源,例如:'locales': ['en', 'de'] 对应的文件路径 en: require('./locales/en.json'), de: require('./locales/de.json'), }, interpolation: { escapeValue: false, // 取消转义HTML特殊字符 }, }); ``` 3. 配置React: 在`App.js`或组件中引入`react-i18next`并使用`<Translation>`或`useTranslation` Hook: ```javascript import { AppProvider, useTranslation } from 'react-i18next'; function App() { const { t } = useTranslation(); return ( <AppProvider> {/* 你的组件代码 */} <h1>{t('greeting')}</h1> // 使用t函数访问翻译后的文本 </AppProvider> ); } ``` 4. 动态加载语言: 使用`i18next.changeLanguage`方法在用户切换语言时更新语言: ```javascript function changeLanguage(newLang) { i18n.changeLanguage(newLang).then(() => { // 异步处理成功后执行 }); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值