在组件外部访问React上下文

reactjs React.js

卡卡西逆天

2020-03-23

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

组件/语言环境/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 };

pages / _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这可能吗?

第2780篇《在组件外部访问React上下文》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
路易飞云 2020.03.23

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

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

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android