在组件外部访问React上下文

时间:2019-01-14 12:10:21

标签: reactjs localization next.js contentful

我正在使用React上下文存储NextJS网站的语言环境(例如example.com/en/)。设置如下:

components / 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 };

页面/_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生命周期方法从Contentful CMS API获取数据。看起来像这样:

pages / index.jsx

import { getEntries } from '../lib/data/contentful';

const getInitialProps = async () => {
  const { items } = await getEntries({ content_type: 'xxxxxxxx' });
  return { page: items[0] };
};

在此阶段,我需要使用语言环境进行此查询,因此需要访问以上Local.Consumer中的getInitialProps。这可能吗?

1 个答案:

答案 0 :(得分:1)

根据此处的文档,这似乎是不可能的:https://github.com/zeit/next.js/#fetching-data-and-component-lifecycle 您可以通过将组件包装在上下文的Consumer中来访问React上下文数据,如下所示:

<Locale.Consumer>
  ({locale}) => <Index locale={locale} />
</Locale.Consumer>

但是getInitialProps是针对顶级页面运行的,无法访问这些道具。

您可以通过其他React生命周期方法(例如componentDidMount?)来获取条目吗 然后,您可以将项目存储在组件状态。

相关问题