无法将道具从父组件传递给子组件

时间:2021-02-20 12:07:46

标签: javascript reactjs

这是我的父组件 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>
         )}

这是我的子组件 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>
   )}

这是json。

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

我在运行此代码时遇到此错误:TypeError:无法读取未定义的属性“名称”。 基本上,当我使用 console.log 时,我得到了一个空状态,并且由于某种原因 axios 请求没有完成。请注意,当我不传递 Name 组件时(即只是注释掉对 Name 组件的调用),我可以轻松获取数据。 我在这个问题上坚持了很长一段时间。

enter image description here

这是我注释掉 Name 组件时的 JSON。

enter image description here

2 个答案:

答案 0 :(得分:1)

首先,使用传递的 props 初始化 child 的状态不是最佳实践。你可以简单地使用道具。其次,api调用是一个异步过程。道具会立即传递,它们不会等待您的调用完成。因此,您应该应用条件渲染,这样就足够了:

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

答案 1 :(得分:0)

刚刚对康斯坦丁告诉我的内容做了一个小改动。我用这个来调用子组件:

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

它可以解决问题。