反应上下文不起作用

时间:2018-03-12 10:33:35

标签: javascript reactjs

我使用create-react-app生成了一个项目。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import AuthProvider from './AuthProvider';

ReactDOM.render(
  <AuthProvider>
    <App />
  </AuthProvider>,
  document.getElementById('root')
);
registerServiceWorker();

AuthProvider.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class AuthProvider extends Component {

  childContextTypes = {
    test: PropTypes.string
  };

  getChildContext() {
    return {
      test: "Hello World!"
    }
  }

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }
}

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          AuthProvider test: {this.context.test} // NOT WORKING
        </p>
      </div>
    );
  }
}

export default App;

但在{this.context.test}中调用App.js似乎无效。我也没有收到任何错误,所以我在这里有点不知所措。

2 个答案:

答案 0 :(得分:2)

看来App缺少contextTypes声明。

  

If contextTypes is not defined, then context will be an empty object.

尝试

import PropTypes from 'prop-types'

App.contextTypes = {
  test: PropTypes.string
}

答案 1 :(得分:0)

您需要为子项定义contextTypes才能访问它。

根据docs

  

如果未定义contextTypes,则context将是一个空对象。

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          AuthProvider test: {this.context.test} 
        </p>
      </div>
    );
  }
}

App.contextTypes = {
   test: PropTypes.string
}