p.S:我在下面添加了一个经过编辑的代码版本。
我有一些JSON数据,我从中提取医生的值并更新状态,然后我想映射到它上并打印出值。现在它只有一个医生,但后来它可以有多个医生,这就是为什么我想在它上映射并以片段的形式打印值。
在控制台.log我得到这个错误
c-sessionfrag.js:50 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_id')
at handleloop (c-sessionfrag.js:50:1)
这是JSON数据
{
"totalReservations": 1,
"allReservations": [
{
"_id": "62d5f88672dd3fadbeeee7d5",
"userId": {
"_id": "62cf836dbbb2ddfdcca4df4d",
"image": "https://res.cloudinary.com/devsalem/image/upload/v1657766765/YOU/fuiiwkvdxwgczpfkv4d9.jpg",
"name": "Hassan Ibrahim",
"mobilePhone": "01010644258",
"gender": "male",
"email": "nohahassan497@yahoo.com",
"birthDate": "1991-06-04",
"trustContact": "01016166161",
"contactRelation": "mom",
"sessions": [
"Individual Session"
]
},
"doctor": {
"_id": "62cf8f75bb6b1eb825e8ab93",
"image": "https://res.cloudinary.com/devsalem/image/upload/v1657769832/YOU/umf1hkh7mjtasd5zy0vr.jpg",
"name": "ruba hamed",
"mobilePhone": "01222990000",
"gender": "female",
"email": "drruba1111@gmail.com",
"birthDate": "22/4/1980",
"languages": [
"english, spanish, arabic"
],
"licIssuedDate": "22/2/1998",
"licExpiryDate": "22/2/1999",
"profession": "therapist",
"sessionPrice": "400"
},
"startDate": "12:00 pm",
"date": "2022-07-26",
"roomName": "6feb87ad-b0cb-4877-a5ed-44e0c1f79fd8"
}
]
}
但由于某种原因,它没有打印任何内容。这是的数据数组
0: {_id: '62cf8f75bb6b1eb825e8ab93', image: 'https://res.cloudinary.com/devsalem/image/upload/v1657769832/YOU/umf1hkh7mjtasd5zy0vr.jpg', name: 'ruba hamed', mobilePhone: '01222990000', gender: 'female', …}
1: {_id: '62cf8f75bb6b1eb825e8ab93', image: 'https://res.cloudinary.com/devsalem/image/upload/v1657769832/YOU/umf1hkh7mjtasd5zy0vr.jpg', name: 'ruba hamed', mobilePhone: '01222990000', gender: 'female', …}
2: {_id: '62cf8f75bb6b1eb825e8ab93', image: 'https://res.cloudinary.com/devsalem/image/upload/v1657769832/YOU/umf1hkh7mjtasd5zy0vr.jpg', name: 'ruba hamed', mobilePhone: '01222990000', gender: 'female', …}
3: {_id: '62cf8f75bb6b1eb825e8ab93', image: 'https://res.cloudinary.com/devsalem/image/upload/v1657769832/YOU/umf1hkh7mjtasd5zy0vr.jpg', name: 'ruba hamed', mobilePhone: '01222990000', gender: 'female', …}
length: 4
[[Prototype]]: Array(0)
这是我的代码
import React, { Component, Fragment } from "react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import './c-session.css';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPhone, faCalendar } from "@fortawesome/free-solid-svg-icons";
import clientimg from '../../../pictures/0_GettyImages-1333254883.png';
import clientname from '../../../pictures/icons8-name-tag-48.png';
import clientdate from '../../../pictures/Icon material-date-range.png';
import clientsession from '../../../pictures/icons8-question-and-answer-session-with-speech-bubble-48.png';
import clientcall from '../../../pictures/icons8-video-call-64.png';
const CSessionFrag = (props) => {
console.log('hi noha ana l frag');
const navigate = useNavigate();
const token = props.token;
const [date, setDate] = useState();
const doctors = { doctor: [], user: [], startDate: "", date: "", roomName: "", sessionID: "" };
const [doctorsArray, setDoctorsArray] = useState(doctors);
const [doctorsNoha, setDoctorsNoha] = useState([]);
async function noha() {
await setDoctorsNoha([...doctorsNoha, doctorsArray.doctor]);
}
useEffect(() => {
axios.get('/reservation', {
headers: {
'token': token
}
})
.then(res => {
console.log('sesssssssssssion fragment of doctorProfile response', res.data.allReservations[0].doctor);
console.log('sesssssssssssion fragment of doctorProfile response', res.data.allReservations[0].roomName);
setDate(res.data.allReservations[0].date)
const reserv = res.data.allReservations;
async function handleloop(reserv) {
for (var i = 0; i <= reserv.length; i++) {
await setDoctorsArray({
sessionID: reserv[i]._id,
startDate: reserv[i].startDate,
date: reserv[i].date,
doctor: reserv[i].doctor,
user: reserv[i].userId,
roomName: reserv[i].roomName
});
}
console.log('done loop');
}
handleloop(reserv);
noha();
// const allData = reserv[0].doctor;
// setImmediate(res.data.allReservations.date);
}).catch(e => {
console.log('sesion errooooooor', e);
})
}, []);
console.log('l arayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy', doctorsArray.doctor);
console.log('l doctorrrrrrrrrr', doctorsNoha);
return (
<Fragment>
{
doctorsNoha.map(doctor => {
<Fragment key={doctor._id} >
<div className="c-session_card">
<div className="c-session_card_top">
<img className="c-session_card_top_img" src={doctor.image} />
</div>
<div className="c-session_card_middle">
<p className="c-session_card_txt" id="c-session_card_name">
<img className="c-session_card_icon" id="c-session_name" src={clientname} />
{doctor.name}
</p>
<p className="c-session_card_txt" >
<img className="c-session_card_icon" src={clientcall} />
{doctor.profession}
</p>
<p className="c-session_card_txt" id="c-session_date_p" >
<img className="c-session_card_icon" id="c-session_date" src={clientdate} />
{date}
</p>
<p className="c-session_card_txt" id="c-session_date_p" >
<img className="c-session_card_icon" id="c-session_date" src={clientdate} />
{doctor.sessionPrice}
</p>
</div>
<div className="c-session_card_bottom">
<button className="c-session_card_bottom_btn" id="c-session_profile_btn" onClick={() => { navigate('/doctorprofile', { state: { docId: doctor._id } }) }}>Profile</button>
<button className="c-session_card_bottom_btn" id="c-session_call_btn" onClick={() => navigate('/startsession', { state: { docId: doctor._id } })}>
<FontAwesomeIcon
icon={faPhone}
id="c-session_call_btn_icon"
/>
Start Session
</button>
</div>
</div>
</Fragment >
})}
</Fragment >
);
}
export default CSessionFrag;
这是经过编辑的代码,它可以正常工作,但doctorsNoha状态没有更新,在页面加载时,它会创建一个空数组
import React, { Component, Fragment } from "react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import './c-session.css';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPhone, faCalendar } from "@fortawesome/free-solid-svg-icons";
import clientimg from '../../../pictures/0_GettyImages-1333254883.png';
import clientname from '../../../pictures/icons8-name-tag-48.png';
import clientdate from '../../../pictures/Icon material-date-range.png';
import clientsession from '../../../pictures/icons8-question-and-answer-session-with-speech-bubble-48.png';
import clientcall from '../../../pictures/icons8-video-call-64.png';
const CSessionFrag = (props) => {
console.log('hi noha ana l frag');
const navigate = useNavigate();
const token = props.token;
const [date, setDate] = useState();
const doctors = { doctor: [], user: [], startDate: "", date: "", roomName: "", sessionID: "" };
const [doctorsArray, setDoctorsArray] = useState(doctors);
const [doctorsNoha, setDoctorsNoha] = useState([]);
async function nohawait(doctorsArray) {
}
useEffect(() => {
axios.get('/reservation', {
headers: {
'token': token
}
})
.then(res => {
console.log('sesssssssssssion fragment of doctorProfile response', res.data.allReservations[0].doctor);
console.log('sesssssssssssion fragment of doctorProfile response', res.data.allReservations[0].roomName);
setDate(res.data.allReservations[0].date)
const reserv = res.data.allReservations;
async function handleloop(reserv) {
for (var i = 0; i < reserv.length; i++) {
await setDoctorsArray({
sessionID: reserv[i]._id,
startDate: reserv[i].startDate,
date: reserv[i].date,
doctor: reserv[i].doctor,
user: reserv[i].userId,
roomName: reserv[i].roomName
});
setDoctorsNoha(current => [...current, doctorsArray.doctor]);
}
console.log('done loop');
}
handleloop(reserv);
// const allData = reserv[0].doctor;
// setImmediate(res.data.allReservations.date);
}).catch(e => {
console.log('sesion errooooooor', e);
})
}, []);
console.log('l arayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy', doctorsArray.doctor);
console.log('l doctorrrrrrrrrr', doctorsNoha);
console.log('rommmmmnme', doctorsArray.roomName);
return (
<Fragment>
{
doctorsNoha.map(doctor =>
<Fragment key={doctor._id} >
<div className="c-session_card">
<div className="c-session_card_top">
<img className="c-session_card_top_img" src={doctor.image} />
</div>
<div className="c-session_card_middle">
<p className="c-session_card_txt" id="c-session_card_name">
<img className="c-session_card_icon" id="c-session_name" src={clientname} />
{doctor.name}
</p>
<p className="c-session_card_txt" >
<img className="c-session_card_icon" src={clientcall} />
{doctor.profession}
</p>
<p className="c-session_card_txt" id="c-session_date_p" >
<img className="c-session_card_icon" id="c-session_date" src={clientdate} />
{date}
</p>
<p className="c-session_card_txt" id="c-session_date_p" >
<img className="c-session_card_icon" id="c-session_date" src={clientdate} />
{doctor.sessionPrice}
</p>
</div>
<div className="c-session_card_bottom">
<button className="c-session_card_bottom_btn" id="c-session_profile_btn" onClick={() => { navigate('/doctorprofile', { state: { docId: doctor._id } }) }}>Profile</button>
<button className="c-session_card_bottom_btn" id="c-session_call_btn" onClick={() => navigate('/startsession', { state: { docId: doctor._id, roomName: doctorsArray.roomName } })}>
<FontAwesomeIcon
icon={faPhone}
id="c-session_call_btn_icon"
/>
Start Session
</button>
</div>
</div>
</Fragment >
)}
</Fragment >
);
}
export default CSessionFrag;
从0
开始迭代时,必须在数组的长度之前停止迭代
交换这个:
for (var i = 0; i <= reserv.length; i++) {
有了这个:
for (var i = 0; i < reserv.length; i++) {
您收到一个错误,因为reserv[1]
就是undefined
。