我正在编写一个从服务器获取数据的 React Native 应用程序。我需要接收 json 并只返回一些接收到的对象(日期晚于当前对象的对象)。问题发生在中途。
这是我的代码
import {serverURL} from '../assets/config/server'
export const getEventsByRegion = (region) => {
let events;
let url = `${serverURL}events/eventList`
return fetch(url, {
method: 'GET',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();})
.then(responseData => {
events = responseData;
})
.catch(err => {
console.log("fetch error" + err);
})
.then( () =>
{
if(events){
events = Object.values(events).filter((key) => {
console.log(key)
return ((key.region[0] === region) )
})
} else
events = null;
if(events){
events = Object.values(events).filter((key) => {
console.log(key.name, key.time)
console.log(key.time.date)
return (toSimpleDate(new Date(key.time.date)) >= toSimpleDate(new Date()))
})
}
if(events !== undefined) {
return events;
}
}
);
}
toSimpleDate = (date) => {
return date.setHours(0,0,0,0);
}
这是我的 console.log() 输出
//first output - full
//1
Object {
"__v": 0,
"_id": "607e06dd5195440015e95ed6",
"description": "",
"geoLocation": Object {
"_id": "607e06dd5195440015e95ed7",
"geometry": Object {
"coordinates": Array [
null,
null,
],
"type": "Point",
},
"type": "Feature",
},
"inBus": true,
"name": "Test event 1",
"region": Array [
"Region1",
],
"time": Object {
"date": "2021-04-19T22:37:37.055Z",
"timeFrom": "2021-04-19T22:37:37.055Z",
"timeTo": "2021-04-20T10:37:00.000Z",
},
}
//2
Object {
"__v": 0,
"_id": "60911a388446fe0015c8f7e0",
"description": "test description",
"geoLocation": Object {
"_id": "60911a388446fe0015c8f7e1",
"geometry": Object {
"coordinates": Array [
null,
null,
],
"type": "Point",
},
"type": "Feature",
},
"inBus": false,
"name": "Test event 2",
"region": Array [
"Region1",
],
"time": Object {
"date": "2021-05-26T09:54:00.000Z",
"timeFrom": "2021-05-04T08:00:15.410Z",
"timeTo": "2021-05-04T12:25:15.410Z",
},
}
//second output - a part only
//1
Test event 1 Object {
"date": "2021-01-01T12:41:00.000Z",
"timeFrom": "2020-12-27T11:41:48.610Z",
"timeTo": "2020-12-27T12:41:48.610Z",
}
2021-01-01T12:41:00.000Z
//2
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'key.time.date')]
//
如您所见,它拒绝读取 key.time.date 字段(示例中没有显示,但 key.time 和 key.name 都没有问题)。数据的来源是一样的,我找不到结构的问题。
请帮忙