![](/img/trans.png)
[英]React.js | Infinite render if I pass setState as a callback function, even after destructuring props
[英]React setState with callback and pass props
我有一個文件上傳組件(我正在React中工作),它會通過點擊處理程序觸發文件上傳。 我想在上傳過程中顯示加載圖標。 因此,當調用文件處理程序函數時,我的加載狀態設置為true。 但是,狀態更改有時僅在文件上傳開始之前呈現,在此期間瀏覽器凍結。 因此,我四處搜索,發現可以將回調傳遞給setState,該回調將在狀態更改和組件重新呈現后觸發。 但是,在我的情況下,我需要將從事件收集的文件傳遞給此回調函數……但這不起作用。 我努力了:
handleFile(files) {
this.setState({ loading: true }, () => {
console.log(files)
// here is where I want to read the files
})
}
-此日志:文件列表{length:0}
handleFile(files) {
this.setState({ loading: true }, (files) => {
console.log(files)
// here is where I want to read the files
})
}
-此日志未定義。
有什么想法我會出錯嗎? 順便說一句,事件是在另一個函數中處理的,並且事件目標(文件)正在傳遞給handleFiles函數,問題似乎出在將文件傳遞給回調函數。
謝謝
我建議使用Promise處理異步請求; 像axios這樣的庫效果很好。 然后,您可以輕松管理狀態更改。 例如:
handleFile(url, files) {
this.setState({
loading: true
});
axios.post(url, {
data: files
}).then(response => {
this.setState({
loading: false
});
})
.catch(error => {
console.log('Error posting data.', error);
this.setState({
error: true
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.