【问题标题】:React.js: Props not being received by child componentReact.js:子组件未收到道具
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    应该是this.state.sessionCode。您正在传递 this.state.enteredCode

    【讨论】:

    • 谢谢!这是漫长的一天哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2021-11-25
    • 2018-02-19
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多