Javascript 无法读取属性';设置状态';未定义的类型-转换为箭头函数
我试图在函数中设置状态。通常我只是将其转换为一个箭头函数或绑定它来解决问题,但是如果我将此特定函数转换为一个箭头函数,则无法得到所需的结果(这是一个图像映射响应,将在openlayers 6中用作层)。我怀疑这是因为Javascript 无法读取属性';设置状态';未定义的类型-转换为箭头函数,javascript,reactjs,Javascript,Reactjs,我试图在函数中设置状态。通常我只是将其转换为一个箭头函数或绑定它来解决问题,但是如果我将此特定函数转换为一个箭头函数,则无法得到所需的结果(这是一个图像映射响应,将在openlayers 6中用作层)。我怀疑这是因为这个.response回调函数中的部分代码 这是密码 this.makeRequest(newSrc, function() { const arrayBufferView = new Uint8Array(this.response)
这个.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上的映射。对于上下文,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
的代码不应负责更新状态。
另外,为了更容易调试,不要太依赖绑定,只需将响应作为回调参数给出即可
这应该起作用:
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);
});
试试这个,我希望它能起作用
onLoad函数不是一个箭头函数(我希望),这就是它不起作用的原因。如果您可以发布代码的其他部分,例如调用函数的位置和方式,则会有所帮助。从另一个加载新ImageWMS层的函数调用Edit。这是内置的imageLoadFunction的一部分OpenLayers@JosephD. 这是一个类组件我相信回调函数应该将响应作为参数,例如,
this.makeRequest(newSrc,(response)=>{/*应该能够在这里访问响应和setState*/})
@Jayce444谢谢我刚才也尝试过,但现在仍然没有显示映射数据:(
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.bind(this)
client.send()
}