每当我的对象键中有 URL 时,我都会通过获取字符串来对对象进行一些格式化。当我在提取结束时设置状态时,显示的组件正在使用预格式化的对象。
该对象正确显示在为组件提供的道具的 console.log 中,以及控制台是否在函数结束时记录。
为什么 SetState 使用原始对象而不是 promise 的结果?
_clicked(index) {
let clickedHouse = this.state.houses.find(obj => obj.url === index);
delete clickedHouse[`url`];
this._getNames(clickedHouse).then(res =>
// console.log(`completedFetching`,res)
this.setState({displayedHouse: res})
)
}
_getNames(houseObj) {
return new Promise((resolve, reject) => {
let namedHouse = houseObj;
Object.keys(namedHouse).forEach(key => {
if (namedHouse[key].includes(`https`)) {
console.log(`fetching something`)
this._loadJson(namedHouse[key])
.then(result => (namedHouse[key] = result.name));
}
});
resolve(namedHouse)
})
}
目标是显示:https://anapioficeandfire.com/api/houses/10 使用名称而不是 URLS。