我有一个在 getServerSideProps 中使用 next-i18next 的下一页,我还有另一个使用 getServerSideProps 从 MongoDB 中提取数据的页面。两者都能正常工作。
我希望能够将 next-i18next 添加到连接到 Mongo 的函数中(基本上结合了 getServerSideProps 函数),但出现错误:
nexti18n-next 错误:初始语言环境参数未传递到 serverSideTranslations'
第一个页面的getServerSideProps函数连接next-i18n
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,})(async ({ locale, }) => {
return {
props: {
...(await serverSideTranslations(locale,
[
'language-file',
...
]
)),
},
};
})
第二页中的 getServerSideProps 函数从 Mongo 中拉取数据:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
是否可以将 next-i18next 代码“添加”到第二个函数?在我看来,每个函数中定义“语言环境”和“上下文”的方式不同是个问题。我已经尝试了很多两者的组合,但最终弄乱了 mongo 查询或翻译。
这就是我认为它会完成的方式:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context,{ locale, }) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
...(await serverSideTranslations(locale,
[
'language-files',
...
]
)),
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
非常感谢任何可能的帮助!