我正在从API获取数据。我需要将该数据推送到一个类。下面是我的基本类结构:
Attendance.js
class Attendance{
constructor(SessionDate,SubjectName,Att){
this.SessionDate = SessionDate;
this.SubjectName = SessionDate+'-'+SubjectName;
this.Att = Att;
}
}
export default Attendance ;
这是我的动作课:
attendance.js
import Attendance from "../../models/Attendance";
import {AsyncStorage} from 'react-native';
export const SET_STUDENT_ATTENDANCE = 'SET_SET_STUDENT_ATTENDANCE';
export const fetchStudentAttendance = (newDate) => {
return async (dispatch,getState) =>{
const userData = await AsyncStorage.getItem('userData');
const transformedData = JSON.parse(userData);
const { token } = transformedData;
const Date = newDate;
try{const response = await fetch(
`http://........./api/stud/Get_Stud_Attendance_Details?Date=${Date}`,
{
headers: {
'Content-Type': 'application/json',
'Authorization':token
},
}
);
const resData = await response.json();
console.log(resData);
const loadedStudentAtt = [];
loadedStudentAtt.push(new Attendance(
resData["WeeklyAttendanceList"].SessionDate,
resData["WeeklyAttendanceList"].SubjectAbbr,
resData["WeeklyAttendanceList"].Att,
));
console.log(loadedStudentAtt);
dispatch({type: SET_STUDENT_ATTENDANCE,studentattendance:loadedStudentAtt});
}
catch(err){
console.log(err);
throw err;
};
};
};
以下是示例API数据:
Object {
"Error": null,
"Response": null,
"StartDate": "2020-02-04T00:00:00",
"StudentAttendancePercentList": Array [],
"Successful": true,
"WeeklyAttendanceList": Array [
Object {
"Att": "1",
"SessionDate": "28 Jan 2020",
"SessionDayName": "",
"SessionNo": 1,
"SessionTiming": "09:15 - 10:30",
"SubjectAbbr": "Subject1",
},
Object {
"Att": "0",
"SessionDate": "28 Jan 2020",
"SessionDayName": "",
"SessionNo": 1,
"SessionTiming": "09:15 - 10:30",
"SubjectAbbr": "Subject2",
},
],
}
我在console.log()中获得的数组如下:
Array [
Attendance {
"Att": undefined,
"SessionDate": undefined,
"SubjectName": "undefined-undefined",
}, ]
您能告诉我我是否将数据正确地推送给班级吗?
预先感谢。
答案 0 :(得分:0)
WeeklyAttendanceList是对象数组。因此,您必须对其进行迭代,然后将数据推送到loadedStudentAtt。
const resData = await response.json();
console.log(resData);
const WeeklyAttendanceList = resData.WeeklyAttendanceList;
const loadedStudentAtt = [];
WeeklyAttendanceList.forEach(item => {
loadedStudentAtt.push(new Attendance(
item.SessionDate,
item.SubjectAbbr,
item.Att,
))
})
console.log(loadedStudentAtt);