【发布时间】: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)) 中打印结果时,我得到了正确的输出。有谁知道这个问题的根源吗?
【问题讨论】: