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

时间:2018-07-09 14:46:41

标签: javascript reactjs react-context

我有一个名为GlobalDataProvider的React类:

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类吗?还是只有Context变量?

2 个答案:

答案 0 :(得分:3)

我怀疑您需要将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>
 );
};

答案 1 :(得分:2)

尝试:

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