如何从父组件刷新子组件

时间:2020-02-29 23:36:51

标签: reactjs

我有一个页面,允许用户上传和显示照片。后端API已全部内置。我的问题是成功上传照片后,我需要刷新页面才能在页面底部看到新照片。以下是相关代码:

父组件

refreshPage = (value) =>  {

    if(this.state.photoUploaded)
    {
        //this refreshes the API call to get the new photo
        this.componentDidMount();
    }    
};

async componentDidMount(){
    const url = <the url of my API>;
    const response = await fetch(url);
    const data = await response.json();
    this.setState({eventdata:data});

    var i = 0;
    for(i = 0; i < data.photos.length; i++)
    {
       this.state.photos.push({"url":data.photos[i].url});
    }
    this.setState({loading:false});
}

render(){
    <div>
        <PhotoSelectorComponent eventdata={this.state.eventdata} refreshPage={this.refreshPage}></PhotoSelectorComponent>
        <PhotoDisplayComponent photos={this.state.photos} eventdata={this.state.eventdata} refreshPage={this.refreshPage}></PhotoDisplayComponent>
    </div>
}

当照片上传后,我有PhotoSelectorComponent通知父组件。它调用RefreshPage函数,该函数调用componentDidMount(),这使api调用了额外的时间,并且我在照片数组中看到了新照片。我什至不确定这是否是实现此目的的最佳方法,但这是我根据所读内容尝试过的一种想法,并且它正在起作用。但是我现在不确定如何重新渲染PhotoDisplayComponent。我正在更新状态,但没有刷新页面。我非常接近完成这项工作,但是我不确定他们是否以目前的方式设置它是最佳实践。我觉得只要所有连线正确,页面都应该刷新一下。

1 个答案:

答案 0 :(得分:0)

您在这里有一些基本的React错误,例如直接更改状态和在同一函数中几次调用setState。试试这个:

async componentDidMount() {
    const url = 'someurl';
    const response = await fetch(url);
    const data = await response.json();   

    const newPhotos = data.photos.map((photo) => {
      return { "url": photo.url }
    })


    this.setState(({
      loading: false,
      photos:[...this.state.photos,...newPhotos],//I dont think you actually get only new photos, but following your code...
      eventdata: data
    }));
  }

我还认为您的体系结构没有多大意义,因为我从未见过直接调用componentDidMount的情况。