【发布时间】:2017-08-05 19:20:47
【问题描述】:
我试图将状态变量作为道具传递给子组件,但子组件没有收到任何东西。我在某处看到状态变量不会立即更新,因此我将调用将两个子组件交换到 setState 回调函数中。这是一些代码..
父组件
//function called by app component to unmount from parent
handleLandingUnmount(enteredCode){
console.log(enteredCode + ' received in index.js');
//updating state to give enteredCode to be passed to Chatpage component in props
this.setState({sessionCode: enteredCode}, function(){
this.onSessionInState();
});
}
onSessionInState(){
console.log(this.state.sessionCode);
this.setState({renderLandingScreen:false});
this.setState({renderChatScreen:true});
}
render(){
//if app component has unmounted, check if chat screen is to be rendered and pass the code as a prop
const toRender = this.state.renderLandingScreen?<App unmount={this.handleLandingUnmount}/>:
this.state.renderChatScreen?<Chatpage sessionCode={this.state.enteredCode}/>:<h1>Something else could go here...</h1>;
return toRender;
}
聊天页面组件
constructor(props){
super(props);
console.log(JSON.stringify(props));
}
render(){
return(
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>{this.props.sessionCode}</h2>
</div>
</div>
);
}
提前感谢您的帮助。
【问题讨论】:
-
你将
sessionCode传递给Chatpage而不是App -
这就是它应该的方式。抱歉,代码可能很模糊! App 组件被卸载,然后父组件将返回的代码作为 prop 传递给 chatpage 组件。
-
请更新您的问题,不清楚哪个组件是哪个
-
@GershonPapi 更新了!
标签: javascript reactjs state