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
}
添加回答
举报