请原谅我的代码
从外部来源,我得到以下external data which I name loxAP3
我试图首先使用以下代码来检索与rooms.image属性相关的svg数据,然后更改传入的svg数据以进行反应。
createRoomData(loxAPP3, socket) {
console.log(loxAPP3)
let rooms = []
let rawRooms = loxAPP3.rooms
for (const rawRoom in rawRooms) {
rooms.push(rawRooms[rawRoom])
}
//add svg property with blank property value
rooms.forEach((room) => {
room.svg = ''
})
//fetch image data for each room in loxApp3.rooms
rooms.forEach((room) => {
const image = room.image
socket
.send(image)
.then(function(respons) {
//console.log("Successfully fetched svg image " + respons ); // success
room.svg = respons
//console.log(room.svg) // success console returns room.svg data
},
function(err) {
console.error(err);
}
);
})
this.setState({
rooms: rooms
}, () => {
console.log(rooms) // success rooms[0].svg is shown as having been populated
this.adjustSvGImageToReact()
})
}
console.log(rooms) // success rooms[0].svg is shown as having been populated
但是,当我尝试操作room对象时出现问题,如果我记录了原始数据中已经存在的属性,就没有问题,但是,如果我尝试获取.svg属性,它返回的并不是未定义的但是作为空字符串,我首先将其设置为。
adjustSvGImageToReact() {
this.state.rooms.forEach((room)=>{
console.log(room.name) // success
console.log(room.uuid) // success
console.log(room.svg) //empty
})
}
答案 0 :(得分:0)
创建一个socket.send()
承诺的数组,而不是在forEach
内部调用它们
然后,您可以使用Promise.all()
设置状态,并在套接字请求完成后调用adjustSvGImageToReact()
const svgPromises = rooms.map((room) => {
const image = room.image
return socket
.send(image)
.then((respons)=> room.svg = respons)
})
Promise.all(svgPromises).then(() => {
this.setState({rooms: rooms}, () => {
console.log(rooms) // success rooms[0].svg is shown as having been populated
this.adjustSvGImageToReact()
});
}).catch(err=>console.log('One of the socket requests failed'))