javascript - "this.context"返回一个空对象

标签 javascript reactjs

我不明白为什么:

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

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

这是我的sandbox

这是我的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;

为什么this.context为空?

任何提示都会很棒, 谢谢

最佳答案

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

关于react website无论如何,它指定了这么多。

所以唯一需要改变的是:

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;

希望这有帮助!

关于javascript - "this.context"返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612744/

相关文章:

python - 将输入从React.js/Electron应用传递到Python脚本?

javascript - React redux applyMiddleware 不是一个函数

reactjs - 重新加载 React Router 应用程序时出现 404 错误

Javascript 从嵌套数组中删除键

javascript - 战胜 jQuery 成瘾 : Which jQuery methods are easily translated into pure javascript?

reactjs - Ant 设计 - 如何在每次选择后自动关闭选择 ("tags"或 "multiple"模式)下拉列表?

reactjs - 在函数或类中使用 `useDispatch` 可以吗?

javascript - 单击网页屏幕截图时鼠标消失

javascript - 切换光标以显示我可以放置元素的位置

javascript - CSS/JS 动态缩小? (表现)