React.js:子组件未接收到道具

时间:2017-08-05 19:20:47

标签: javascript reactjs state

我正在尝试将状态变量作为prop传递给子组件,但子组件没有收到任何内容。我看到某个状态变量没有立即更新,所以我调用了两个子组件交换到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>
    );
}

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

当代码存储在this.state.sessionCode中时,您似乎正在传递this.state.enteredCode

答案 1 :(得分:1)

应该是this.state.sessionCode。你传入this.state.enteredCode