“this.context”返回一个空对象

Web*_*man 3 javascript reactjs

我不明白为什么:

  • 我有react_react-dom 16.8x
  • 我的提供者和消费者之间有一个组件,以避免上述两个元素之间的循环调用。

我希望我的上下文可以直接在生命周期组件中访问,并且看到 ReactJS 提出了this.context's 方法来做到这一点。

这是我的沙箱

这是我的reactjs片段

import React, {Component}from "react"; 
import "./App.css";


// first we will make a new context
const MyContext = React.createContext();

// Then create a provider Component
class MyProvider extends Component {
  state = {
    name: 'Wes',
    age: 100,
    cool: true
  }
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        growAYearOlder: () => this.setState({
          age: this.state.age + 1
        })
      }}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

const Family = (props) => (
  <div className="family">
    <Person />
  </div>
)

class Person extends Component {

  componentDidMount(){ 
    console.log("context: ", this.context)
  }
  render() {
    console.log("context: ", this.context)
    return (
      <div className="person">
        <MyContext.Consumer>
          {(context) => (
            <React.Fragment>
              <p>Age: {context.state.age}</p>
              <p>Name: {context.state.name}</p>
              <button onClick={context.growAYearOlder}></button>
            </React.Fragment>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}


class App extends Component {
  render() {
    return (
      <MyProvider>
        <div>
          <p>I am the app</p>
          <Family />
        </div>
      </MyProvider>
    );
  }
}


export default App;
Run Code Online (Sandbox Code Playgroud)

为什么this.context是空的?

任何提示都会很棒,谢谢

小智 5

您需要设置 contextType 来使用上下文。

无论如何,在反应网站上它指定了这么多。

所以唯一需要改变的是:

class Person extends Component {
  componentDidMount(){ 
    console.log("context: ", this.context)
  }
  render() {
    console.log("context: ", this.context)
    return (
      <div className="person">
        <MyContext.Consumer>
          {(context) => (
            <React.Fragment>
              <p>Age: {context.state.age}</p>
              <p>Name: {context.state.name}</p>
              <button onClick={context.growAYearOlder}></button>
            </React.Fragment>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}
Person.contextType = MyContext;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!