2 回答

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

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
你不能使用直接改變狀態(tài),所以顯示一些錯(cuò)誤。您應(yīng)該使用 來(lái)更新?tīng)顟B(tài)中的某些密鑰。在代碼中,執(zhí)行以下操作: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
更多信息
你應(yīng)該用箭頭函數(shù)代替普通函數(shù)這行:普通函數(shù)在代碼運(yùn)行時(shí)發(fā)生變化,你可以得到你需要的。thisthis
function() {
if (xhr.readyState === 4) {
// doing something with this will not work well
}
}
箭頭函數(shù)完成時(shí)代碼運(yùn)行時(shí)不會(huì)更改,您可以使用這個(gè)簡(jiǎn)單的功能。this
()=>{
//do something with this
}
添加回答
舉報(bào)