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
中定义的myisInGame
是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>