[英]Remount reactjs component
我的React應用程序中有兩個組件可以從API獲取數據。 一個接收圖像,另一個接收文本。
我在頁面底部有一個按鈕,我想用它來刷新這兩個組件。
它的行為就像刷新整個頁面一樣,但是我認為這不是最好的方法,因為我正在使用組件。
我發現一些解決方案說要更新密鑰,但這不適合我的問題。 我首先要重建我的組件,以便它將執行來自外部api的HTTP請求。
我將使用其中一個組件作為示例,因為它們非常相似:
componentDidMount() {
axios.get("https://dog.ceo/api/breeds/image/random")
.then(res => {
console.log(res)
this.setState({wiseDog:res.data.message})
this.setState({isLoading:false})
})
.catch( err => {
this.setState({error:err.data.message})
})
}
當安裝組件時,我在html上渲染wiseDog狀態(這是我的圖像鏈接),並且可以工作。 我想從我的頁腳組件中單擊一個按鈕,這將發出一個新請求來更新圖像。
<Fragment>
<CssBaseline />
<AppBar position="fixed" color="primary" className={classes.appBar}>
<Toolbar className={classes.toolbar}>
<Fab color="secondary" aria-label="Add" className={classes.fabButton}>
<Refresh />
</Fab>
</Toolbar>
</AppBar>
</Fragment>
該按鈕是<Refresh/>
有誰知道我可以搜索或嘗試解決的問題?
您可以將API調用的代碼放入函數中,並在該FAB的componentDidMount
和onClick
時調用它。
class MyComponent extends React.Component {
componentDidMount(){
this.requestUpdate();
}
requestUpdate = () => {
// Make API call here and 'setState' when it completes
};
render(){
return (
<Fragment>
<CssBaseline />
<AppBar>
<Toolbar>
<Fab onClick={this.requestUpdate}>
<Refresh />
</Fab>
</Toolbar>
</AppBar>
</Fragment>
);
}
}
您的刷新組件將使用相同的API,並將響應保存在本地狀態,並將該狀態作為prop通過父組件傳遞給另一個子組件,然后再次渲染圖像和文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.