首页 > 解决方案 > 传递给子组件的父组件状态未定义

问题描述

在我的父组件中,我有一个发出 GET 请求的函数。我将响应 JSON 存储在父组件的状态中,并将状态传递给子组件,然后子组件以特定格式呈现响应(在此,它填充一个表)。

这是父组件的代码:-

ParentComponent { 
   sendGETRequest() {
    /* Fetch API code */
    .then(response => response.json())
    .then(response => {
            this.setState({
                    personData: response
            });
            console.log(this.state.personData); //loads late 
    });
   }

   render() {
      return(
      <Link to="/PersonData/ViewPerson">
      <input onClick={this.sendGETRequest} />

      <Route
            path="/PersonData/ViewPerson"
            render={() => <ViewPersonTable pData={this.state.personData} />}
      />
    );
   }
}

这是子组件的代码:-

ChildComponent{
    render(){
       console.log(this.props.pData); //This loads before the console.log in parent and is undefined 
       return(
       );
     }
 }

我的问题是,据我所知,setState 发生在子组件已经呈现之后,因此我传递给子组件的状态是“未定义”。我该如何解决?

标签: reactjs

解决方案


您可以使用条件渲染;

  <Route
        path="/PersonData/ViewPerson"
        render={() => this.state.personData ? <ViewPersonTable pData={this.state.personData} /> : null}
  />

推荐阅读