我有一个名为的 React 类GlobalDataProvider
:
import React, { Component } from 'react';
const DataContext = React.createContext();
export default DataContext;
export class DataProvider extends Component {
state = {
title: 'Some title'
}
render() {
return (
<DataContext.Provider
value={{state: this.state}}>
{this.props.children}
</DataContext.Provider>
)}
}
我正在尝试在另一个文件“PageSection.js”中使用数据,如下所示:
import React from 'react';
import DataContext from '../data/GlobalDataProvider';
const PageSection= () =>{
return (
<section className="page-section">
<DataContext.Consumer>
{(context) => (
<h1>{ context.state.title }</h1>
)}
</DataContext.Consumer>
</section>
);
};
但是,由于某种原因,这不起作用。我收到此错误消息:
TypeError: Cannot read property 'state' of undefined,
in PageSection.js line 11 (the line with this code: { context.state.title }).
我究竟做错了什么?
我必须导入类 DataProvider 吗?还是只有上下文变量?