2 回答

TA貢獻1777條經驗 獲得超10個贊
在此行上使用箭頭函數表達式,其他明智的將被覆蓋。箭頭函數表達式將頂級綁定到函數。像這樣做:xhr.onreadystatechange = function() {
this
this
xhr.onreadystatechange = () => {...}

TA貢獻1830條經驗 獲得超3個贊
你不能使用直接改變狀態,所以顯示一些錯誤。您應該使用 來更新狀態中的某些密鑰。在代碼中,執行以下操作:this.state.keythis.state.imagesIDthis.setState({someKey:newValue})
// get a new imagesID base on old value
const newImagesID = [...this.state.imagesID,'exampleId']
//this.state.imagesID = newImagesID // dont do this
this.setState({imagesID:newImagesID}) //use new value to update key
更多信息
你應該用箭頭函數代替普通函數這行:普通函數在代碼運行時發生變化,你可以得到你需要的。thisthis
function() {
if (xhr.readyState === 4) {
// doing something with this will not work well
}
}
箭頭函數完成時代碼運行時不會更改,您可以使用這個簡單的功能。this
()=>{
//do something with this
}
添加回答
舉報