Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React-context-API-can';t从子提供程序更新父消费者_Reactjs - Fatal编程技术网

Reactjs React-context-API-can';t从子提供程序更新父消费者

Reactjs React-context-API-can';t从子提供程序更新父消费者,reactjs,Reactjs,我有以下两个类组件: Class App extends Component { constructor(props) { super(props); this.state = ({}); } render() { return ( <div className="App"> <GameContext.Consumer> {value => value.isInGame ? <

我有以下两个类组件:

Class App extends Component {
  constructor(props) {
    super(props);
    this.state = ({});
  }

  render() {
    return (
      <div className="App">
        <GameContext.Consumer>
          {value => value.isInGame ? <Game /> : <h1>Not in game</h1>}
        </GameContext.Consumer>
      </div>
    );
  }
}
因此,默认情况下,
GameContext
中定义的my
isInGame
true
。然后,应用程序呈现作为提供者包装的
游戏
组件,并传递一个从未到达应用程序(消费者)的值

使用
React.createContext({isInGame:true})
正确导入和创建上下文

还尝试在应用程序中使用静态
contextType
,而不是将其包装为消费者,但没有成功。我错过了什么?提前谢谢。

您的
内有
。上下文中的默认值={}(React.createContext({}))。所以应用程序永远不会进入
组件

原因:

<GameContext.Consumer>
  {value => value.isInGame ? <Game /> : <h1>Not in game</h1>}
</GameContext.Consumer>

{value=>value.isInGame?:不在游戏中}

value.isInGame未定义=>从不进入
编辑的我的帖子,默认值为isInGame:true,游戏组件不会被渲染。
<GameContext.Consumer>
  {value => value.isInGame ? <Game /> : <h1>Not in game</h1>}
</GameContext.Consumer>