reactjs - 访问组件外部的 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
。这可能吗?
解决方案
根据此处的文档,这似乎是不可能的:https://github.com/zeit/next.js/#fetching-data-and-component-lifecycle 您可以通过将组件包装在上下文的 Consumer 中来访问 React 上下文数据像这样:
<Locale.Consumer>
({locale}) => <Index locale={locale} />
</Locale.Consumer>
但是 getInitialProps 是针对顶级页面运行的,并且无法访问道具。
你能在另一个 React 生命周期方法中获取你的条目,比如componentDidMount 吗? 然后您可以将您的项目存储在组件状态中。
推荐阅读
- python - 无法拆分文本文件中的每一行
- python - 尝试将新数据插入到 mongo db 中,该数据库可能故意包含重复项
- mysql - sql查询 | 处理具有潜在空值的多个 where 条件
- mysql - nodejs + express + mysql 无法在后端得到任何响应
- javascript - d.getMilliseconds() 调用将毫秒格式化为始终为 3 位数
- javascript - 嵌套 AJAX 调用帮助 Angular JS
- php - 显示表的值及其外键
- javascript - 多个输入类型=文本和输入类型=颜色的Javascript通用函数
- c - 为什么分叉我的进程会导致文件被无限读取
- assembly - 警告 A6004:过程参数或本地未引用:地址 MASM 程序集