我正在尝试将数据从mongo提取到客户端以进行响应。 我成功通过数据库的端点API将组件的状态设置为正确的字段。 但是,当我想打印状态以查看控制台是否工作时,尽管状态发生了变化,但我还是在控制台中看到了一个空对象。[在此处输入图像描述] [1]
getDataFromDb = () => {
const req = new Request('http://localhost:5000/family',{
method: 'GET',
cache: 'default'
});
fetch(req).then(res=>{
return res.json();
}).then(data=>{
console.log(data);
this.setState({
rooms: data
});
console.log(this.state.rooms);
}).
catch(err=>{
console("Error: " + err);
});
};
componentDidMount() {
this.getDataFromDb().then(result => this.setState({rooms: result}));
//let rooms = this.formatData(this.getDataFromDb());
//let featuredRooms = ...rooms.filter(room => room.featured===true);
//let maxPrice = Math.max(...rooms.map(item=>item.price));
//let maxSize = Math.max(...rooms.map(item=>item.size));
//new code:
let featuredRooms = this.state.rooms.filter(room=>room.featured===true);
let maxPrice = Math.max(this.state.rooms.map(item => item.price));
let maxSize = Math.max(this.state.rooms.map(item=> item.size));
this.setState({
// old code ---> rooms,
//rooms,
featuredRooms,
sortRooms: this.state.rooms,
//old code
//sortedRooms:rooms,
loading:false,
price:maxPrice,
maxPrice,
maxSize
});
this.printData();
}
答案 0 :(得分:0)
在反应中,setState
是一个异步函数。打印状态(仅在更改状态后)不会提供最新状态。如果要在设置状态后触发功能,可以执行以下操作:
this.setState({
// old code ---> rooms,
//rooms,
featuredRooms,
sortRooms: this.state.rooms,
//old code
//sortedRooms:rooms,
loading:false,
price:maxPrice,
maxPrice,
maxSize
}, () => { this.printData(); });