首页 > 解决方案 > 访问组件外部的 React 上下文

问题描述

我正在使用 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 };

页面/_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 获取数据。看起来有点像这样:

页面/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。这可能吗?

标签: reactjslocalizationnext.jscontentful

解决方案


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

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

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

你能在另一个 React 生命周期方法中获取你的条目,比如componentDidMount 吗? 然后您可以将您的项目存储在组件状态中。


推荐阅读