在React中未定义上下文值

时间:2019-05-19 18:54:40

标签: javascript reactjs

为什么上下文值显示未定义?

  

src / Context.js:

 keycloak.init({onLoad: 'login-required'}).success(function (authenticated) {
            if (!authenticated) {
                alert('not authenticated');
            } else {
                alert('success');
            }

        }).error(function () {
            alert('failed to initialize');
        });
  

src / country / CountryList.js:

import React, { Component } from 'react';

const Context = React.createContext();

export class Provider extends Component {
  state = { a: 1, b: 2 };
  render() {
    return (
      <Context.Provider value={this.state}>
        {this.props.children}
      </Context.Provider>
    );
  }
}
export const Consumer = Context.Consumer;

试图在CountryList中传递上下文值,但是显示未定义,无法弄清原因。在此先感谢

1 个答案:

答案 0 :(得分:1)

您需要使用Provider封装CountryList组件,即,您需要导入Provider。

import React, { Component } from 'react';
import { Provider,Consumer } from '../../Context';

class CountryList extends Component {
  render() {
    return (
      <Provider>
        <Consumer>
          {value => {
            console.log('val:' + value);
          }}
        </Consumer>
     </Provider>
    );
  }
}
export default CountryList;

此处的Stackblitz示例:https://stackblitz.com/edit/react-143zwt (我只是为了测试而添加。它将为您提供想法。我不在此处添加此代码。)