我想將一個狀態變量作爲道具傳遞給子組件,但子組件沒有收到任何東西。我看到狀態變量不會立即更新的地方,所以我移動了我的調用以將兩個子組件交換到setState回調函數中。下面是一些代碼..React.js:道具不被子組件接收
父組件
//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;
}
Chatpage組件
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'不到'應用程序' –
這就是它應該的方式。對不起,代碼可能非常模糊!應用程序組件被卸載,然後父組件被用來將返回的代碼作爲道具傳遞給聊天頁面組件。 – user4208390
請更新您的問題,不清楚 –