3

我有一个名为的 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 吗?还是只有上下文变量?

4

2 回答 2

4

我怀疑您需要将 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>
 );
};
于 2018-07-09T15:09:08.913 回答
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>
 );
};
于 2018-07-09T14:59:24.377 回答