gpt4 book ai didi

javascript - 无法读取未定义的属性 'setState' - 已转换为箭头函数

转载 作者:行者123 更新时间:2023-11-29 20:28:04 25 4
gpt4 key购买 nike

我正在尝试在函数中设置状态。通常我只是将其转换为箭头函数或绑定(bind)它来解决问题,但是如果我将此特定函数转换为箭头函数我得不到所需的结果(这是一个图像映射响应用作图层开放层 6).我怀疑这是因为回调函数中的 this.response 部分代码。

这是代码。

this.makeRequest(newSrc, function() {
const arrayBufferView = new Uint8Array(this.response)
const blob = new Blob([arrayBufferView], { type: 'image/png' })
const urlCreator = window.URL || (window).webkitURL
const imageUrl = urlCreator.createObjectURL(blob)
tile.getImage().src = imageUrl
this.setState({
isLoading: false
})
})

我已经尝试将其转换为停止 setState 的箭头函数,这不是函数问题,但不会在 fe 上返回 map 。对于上下文,makeRequest 函数是一个新的 XMLHttpRequest

makeRequest = (url, onLoad) => {
this.setState({
isLoading: true
})
const client = new XMLHttpRequest()
client.open('GET', url)
client.responseType = 'arraybuffer'
client.setRequestHeader('Authorization', getCredential())
client.onload = onLoad
client.send()
}

最佳答案

调用makeRequest 的代码不应负责更新状态。此外,为了更容易调试,不要过多依赖绑定(bind),只需将响应作为回调参数给出即可

这应该有效:

makeRequest = (url, onLoad) => {
this.setState({
isLoading: true
});
const client = new XMLHttpRequest();
client.open('GET', url);
client.responseType = 'arraybuffer';
client.setRequestHeader('Authorization', getCredential());
client.onload = () => {
onLoad(client.response);
// Updating "isLoading" should be done only in the function
// doing the network operation
this.setState({
isLoading: false
});
};
client.send();
};


this.makeRequest(newSrc, function(response) {
const arrayBufferView = new Uint8Array(response);
const blob = new Blob([arrayBufferView], { type: 'image/png' });
const urlCreator = window.URL || (window).webkitURL;
tile.getImage().src = urlCreator.createObjectURL(blob);
});

关于javascript - 无法读取未定义的属性 'setState' - 已转换为箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com