【问题标题】:Access React context outside of component访问组件外部的 React 上下文
【发布时间】:2019-06-08 10:18:29
【问题描述】:

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

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] };
};

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

【问题讨论】:

  • 请问你最后是怎么解决的?我面临着一个非常相似的挑战。

标签: reactjs localization next.js contentful


【解决方案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? 然后您可以将您的项目存储在组件状态中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2022-11-02
    • 2016-12-25
    • 2017-12-26
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多