从猫鼬中获取数据

问题描述 投票:0回答:1

我正在尝试将数据从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();
}
reactjs mongodb endpoint
1个回答
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(); });
© www.soinside.com 2019 - 2024. All rights reserved.