【问题标题】:The react context from the child does not change孩子的反应上下文没有改变
【发布时间】:2020-03-23 22:53:01
【问题描述】:

我从类似问题中阅读了解决方案,但没有帮助。
这是我的简单代码:https://codesandbox.io/s/gracious-jennings-ugqzd


import myContext from "./myContext";
import Two from "./Two.js";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: 0
    };
  }

  render() {
    return (
      <myContext.Provider value={this.state}>
        <div className="App">
          <Two />
          <h2>{this.state.number}</h2>
        </div>
      </myContext.Provider>
    );
  }
}

export default App;

我需要对其进行设置,以便它可以在类中的任何位置 更改变量号。 感谢您的帮助。

【问题讨论】:

    标签: reactjs react-context react-16


    【解决方案1】:

    你不能只是改变状态

      componentDidMount() {
        this.context.number = 100;
      }
    

    如果你改变状态,react 不会重新渲染,因为你改变了它。您可以执行以下操作:

    应用内:

    import React from "react";
    import "./styles.css";
    import myContext from "./myContext";
    import Two from "./Two.js";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          number: 0
        };
      }
      increase = ()=> this.setState({number:this.state.number+1})
    
      render() {
        return (
          <myContext.Provider value={{...this.state,increase:this.increase}}>
            <div className="App">
              <Two />
              <h2>{this.state.number}</h2>
            </div>
          </myContext.Provider>
        );
      }
    }
    
    export default App;
    

    两个:

    import React from "react";
    
    import myContext from "./myContext";
    
    class Two extends React.Component {
      static contextType = myContext;
    
      render() {
        return (
          <myContext.Consumer>
            {({ number,increase }) => <h1 onClick={increase}>{number}</h1>}
          </myContext.Consumer>
        );
      }
    }
    
    export default Two;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多