如何从反应上下文中获取数据

How to get data from react context

我有一个名为 GlobalDataProvider 的 React class:

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 }). 

我做错了什么?

我是否必须导入 class DataProvider?或者只有上下文变量?

尝试:

export class DataProvider extends Component {

  state = {
     title: 'Some title'
  }

  render() {
   return (
     <DataContext.Provider 
       value={this.state}>
       {this.props.children}
     </DataContext.Provider>
    )}
}






const PageSection= () =>{

return (
  <DataProvider>
    <section className="page-section">
        <DataContext.Consumer>
            {(context) => (
                <h1>{ context.title }</h1>
            )}
        </DataContext.Consumer>
    </section>
 </DataProvider>
 );
};

我怀疑您需要 DataContext.Consumer 成为 DataContext.Provider 的子元素。像这样...

import React from 'react';
import DataContext, { DataProvider } from '../data/GlobalDataProvider';

const PageSection= () =>{

return (
    <section className="page-section">
      <DataProvider>
        <DataContext.Consumer>
            {(context) => (
                <h1>{ context.state.title }</h1>
            )}
        </DataContext.Consumer>
      </DataProvider>
    </section>
 );
};