我使用React context来存储NextJS网站的语言环境(例如example.com/en/)。安装程序如下所示:
组件/Locale/index.jsx
import React from 'react';
const Context = React.createContext();
const { Consumer } = Context;
const Provider = ({ children, locale }) => (
<Context.Provider value={{ locale }}>
{children}
</Context.Provider>
);
export default { Consumer, Provider };
页面/u app.jsx
import App, { Container } from 'next/app';
import React from 'react';
import Locale from '../components/Locale';
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};
const locale = ctx.asPath.split('/')[1];
return { pageProps, locale };
}
render() {
const {
Component,
locale,
pageProps,
} = this.props;
return {
<Container>
<Locale.Provider locale={locale}>
<Component {...pageProps} />
</Locale.Provider>
</Container>
};
}
}
到现在为止,一直都还不错。现在在我的一个页面中,我从
getInitialProps
生命周期方法。有点像这样:
页面/索引.jsx
import { getEntries } from '../lib/data/contentful';
const getInitialProps = async () => {
const { items } = await getEntries({ content_type: 'xxxxxxxx' });
return { page: items[0] };
};
在此阶段,我需要使用区域设置进行此查询,以便访问
Local.Consumer
在上面
getInitialProps
. 这可能吗?