Reactjs 如何从父组件刷新子组件
我有一个允许用户上传和显示照片的页面。后端API都是内置的。我的问题是在我成功上传照片后,我需要刷新页面以便在页面底部看到新照片。以下是相关代码: 父组件Reactjs 如何从父组件刷新子组件,reactjs,Reactjs,我有一个允许用户上传和显示照片的页面。后端API都是内置的。我的问题是在我成功上传照片后,我需要刷新页面以便在页面底部看到新照片。以下是相关代码: 父组件 refreshPage = (value) => { if(this.state.photoUploaded) { //this refreshes the API call to get the new photo this.componentDidMount(); }
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>
}
refreshPage=(值)=>{
if(this.state.photoUploaded)
{
//这将刷新API调用以获取新照片
this.componentDidMount();
}
};
异步组件didmount(){
常量url=;
const response=等待获取(url);
const data=wait response.json();
this.setState({eventdata:data});
var i=0;
对于(i=0;i
我让PhotoSelectorComponent在上传照片时通知父组件。它调用RefreshPage函数,该函数调用componentDidMount(),使api调用的时间延长,我在照片数组中看到了新照片。我甚至不确定这是否是最好的方法,但这是我根据我所读到的内容尝试的一个想法,它正在发挥作用。但我不确定此时如何重新渲染PhotoDisplay组件。我正在更新状态,但它不会刷新页面。我很快就能做到这一点,但我不确定我目前的安装方式是否是最佳实践。我觉得如果我把所有东西都连接好了,页面应该会自动刷新。这里有一些基本的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的直接调用 解决方案可能涉及组件WillReceiveProps?感谢您的回复!不幸的是,这也有同样的问题。请将您的整个工作代码上传到github或某个游乐场,我会看一看。我的一个队友解决了这个问题。这是一个关于“this.props”的问题。他去掉了“这个”,它开始工作了。我无法解释为什么,但它奏效了。谢谢@i.brod的帮助!