在使用i18next映射数据时,如何解决翻译方面存在问题。似乎无法使用变量,并且由于map函数,如果我从locales
调用任何转换,即使将键设置为cause.id
,它似乎仍在所有项目上呈现。
请查看以下翻译功能以提供帮助。但似乎可以弄清楚。 https://www.i18next.com/translation-function/essentials
我具有以下结构:
components/
models/causes.json
pages/Home.js
pages/_document.js
static/
images/
locales/
en/
dk/
styles/
server.js
这是我的页面主页
import React, { Component } from 'react';
import Router, { withRouter } from 'next/router';
import Link from 'next/link';
import causes from '../models/causes';
import { withNamespaces } from '../i18n';
import i18n from "i18next";
import { reactI18nextModule } from "react-i18next";
i18n
.use(reactI18nextModule)
.init({
fallbackLng: "en",
load: "languageOnly",
ns: ["common"],
defaultNS: "common",
react: {
wait: true,
nsMode: "default"
}
});
class Home extends Component {
static async getInitialProps({ req, res }) {
return { causes }
}
render() {
const { router, causes } = this.props;
const causeId = router.query.causeId;
const cause = causes.find((cause) => {
if (cause.id === causeId) {
return cause;
}
});
return (
<>
<div className="appContainer">
<h1>{this.props.t('heading')}</h1>
{causes.map((cause) => (
<div key={cause.id}>
<h4>{this.props.t('cause-type', cause.type)}</h4>
<h2>{cause.title}</h2>
<p>{cause.desc}</p>
</div>
))}
</div>
</>
);
}
}
export default withNamespaces('common')(Home)
这是我的i18next配置:
const NextI18Next = require('next-i18next').default
module.exports = new NextI18Next({ otherLanguages: ['en', 'de', 'dk', 'jp', 'kr'] })
这是我的server.js
const express = require('express')
const next = require('next')
const { nextI18NextMiddleware } = require('./i18n')
const app = next({ dev: process.env.NODE_ENV !== 'production' })
const handle = app.getRequestHandler();
(async () => {
await app.prepare()
const server = express()
nextI18NextMiddleware(app, server)
server.get('*', (req, res) => handle(req, res))
await server.listen(3000)
console.log('> Ready on http://localhost:3000')
})()