【问题标题】:Res.json/backend express issueRes.json/backend express 问题
【发布时间】:2021-01-12 05:28:11
【问题描述】:

我正在制作我的第一个 MERN 堆栈应用程序。我在从 MongoDB 查询整个集合并将其保存到 React Class 状态时遇到一些问题。以下是我的代码。

class MyMap extends Component{
    constructor(props){
        super(props);
        this.state = {
            data: [],
            addMarker: {},
            strAdd: "",
            displayAdd: "",
            date: "",
            pictureLink: "",
            description: "",
            modalOpen: false,
        };
        this.toggle = this.toggle.bind(this);
        this.addMarker = this.addMarker.bind(this);
        this.getAddress = this.getAddress.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }
    componentDidMount(){
        let res = this.props.loadHouses();
        console.log("Res Component Did Mount");
        console.log(res);
        this.setState({
            data: res
        });
        console.log("Res This State Data");
        console.log(this.state.data);
    }
}
//Backend loadhouses
export const loadHouses = function () {
    return function (dispatch, getState) {
        console.log("Test House Actions!")
        return axios.get('/api/house', tokenConfig(getState))
            .then(res => res.data)
            .catch(function(err) {
                dispatch(returnErrors(err.response.data, err.response.status));
            });
    }
}
///api/house
router.get('/', auth, (req, res) => {
    console.log("test");
    House.find({}, function(err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
            return res.json(result);
        }
      });
});

Console.log(result) 就在此处返回:

[
[0]   {
[0]     _id: 5ffd1c33820fe62e4983cc19,
[0]     address: '1735 York Avenue New York County, New York, 10128, United States',
[0]     latitude: 40.77952599242572,
[0]     longitude: -73.94478734434928,
[0]     pictureLink: 'Test1',
[0]     description: 'Test1',
[0]     date: '2021/1/12',
[0]     __v: 0
[0]   },
[0]   {
[0]     _id: 5ffd227a76485d31bf43aacc,
[0]     address: '220 Cadman Plaza West undefined, New York, 11201, United States',
[0]     latitude: 40.698127335002695,
[0]     longitude: -73.99188065224,
[0]     pictureLink: 'Test',
[0]     description: 'Test',
[0]     date: '2021/1/12',
[0]     __v: 0
[0]   }
[0] ]

我的问题是 loadHouses 函数不会保存到 this.state.data 中。当我尝试打印 res (console.log(res);) 时,我得到了 undefined,这很奇怪,因为当我在后端请求 (console.log(result)) 中打印结果时,我得到了正确的输出。有谁知道这个问题的根源吗?

【问题讨论】:

    标签: reactjs express axios


    【解决方案1】:

    Axios 调用是 Promise,因此当 loadHouses 返回 axios 调用时,它会返回一个 Promise - 这意味着您要么必须等待它,要么执行 .then 链关闭它,例如

    this.props.loadHouses()
        .then(data => {
            this.setState({
                ...this.state,
                data
            });
        })
    

    此外,React 中的状态更改是异步的,因此您不能在调用 setState 之后立即调用 console.log(this.state.data) 并期望它被更改。最简单的解决方案是在渲染函数的顶部打印您的状态,因为渲染被称为 状态更新后,因此将具有最新值

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2019-07-02
      • 2015-08-07
      • 2022-12-26
      相关资源
      最近更新 更多