简体   繁体   中英

Unable to pass props to child Component from Parent Component

Here is my parent component Search.js

class Search extends Component {
state = {
    hcps: [],
}

componentDidMount() {
    this.fetchingData();
}

fetchingData = () => {
    axios.get('/hcp-overview-panel')
    .then(res => {
        const hcps = res.data;
        console.log('data from fetch: ', hcps)
        this.setState({hcps: hcps},()=>{console.log('state after state: ',this.state)})
    })
    .catch(error => console.error(`Error: $(error)`));
}

render() {
    console.log('State: ',this.state);
    return(
         <div>
           <Name hcps={this.state.hcps} />
         </div>
         )}

And this is my child component Name.js.

class Name extends Component {

state = {
    hcpFromSearch: this.props.hcps,
    data: [28, 48, 40, 19],
    labels: ["In Person Call", "RTE", "MobilePush", "Speaker Program"],
};
 render() {
   console.log('from search:', this.props.hcps)
   return (
<div>
 <div>
    <h2 class="no-margins">
       {this.state.hcpFromSearch.hcp_overview.name}
    </h2>
  </div>
</div>
   )}

This is the json.

   "hcp_overview" : {
            "name" : "Martin Alan Menter, MD, FAAD",
            "designation": "snlam",
            "specialty": "sksn",
            "top_affiliation": "snksn",
            }

I'm getting this error in running this code: TypeError: Cannot read property 'name' of undefined. Basically, when I console.log, I'm getting an empty state and for some reason the axios request isn't getting done. Mind you, when I don't pass the Name component (that is just comment out that call to the Name component), I can fetch the data easily. I'm stuck on this for quite some time.

在此处输入图像描述

And this is the JSON when I comment out the Name component.

在此处输入图像描述

First of all, it is not a best practice to initialize state of child using passed props. You can simply use props. Second, api call is an asynchronous process. Props are passed immediately, they are not waiting for your call to be completed. Thus, you should apply conditional rendering, something like that would suffice:

<div>
  {this.state.hcps.length !==0 && <Name hcps={this.state.hcps}/>}
</div>

Just made a minor change in what Konstantin told me. I called the child component using this instead:

 <div>
    {this.state.hcps.length !==0 && <Name hcps={this.state.hcps}/>}
 </div>

It does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM