React遍历API数据渲染多<Doctors />组件问题求助
解决React遍历医生数据只渲染第一条的问题
你代码里的核心问题很明确:
- 虽然把
drInfo初始化成了数组,但showInfo函数只处理并存储了单个医生对象,而且调用时只传了index=0,导致state里永远只有第一个医生的数据。 - 渲染时用
[drInfo]把单个对象包装成数组再map,自然只会渲染一个组件。
修改后的完整代码:
const [drInfo, setDrInfo] = useState([]); useEffect(() => { const url = "https://.../homepage/consts_list_homepage"; fetch(url, { headers: { "Content-Type": "application/json", }, }) .then((response) => response.json()) .then((data) => { // 直接处理所有医生数据并存入state if (data && data.data && data.data.length > 0) { const doctorsList = data.data.map(doctor => ({ name: doctor.Fname, lname: doctor.Lname })); setDrInfo(doctorsList); } }) .catch((error) => console.error(error)); }, []); return ( <div> {/* 直接遍历drInfo数组,渲染所有医生组件 */} {drInfo.map((doctor, index) => ( <div key={index}> <Doctors info={doctor} /> </div> ))} </div> );
关键修改点:
- 删掉多余的
showInfo函数,直接在fetch回调里用map处理整个医生数据数组,转成你需要的格式后更新state。 - 渲染时直接遍历
drInfo数组,不用再额外包装一层数组。 - 暂时用
index作为key,后续如果API返回唯一ID(比如doctor.id),记得替换成唯一值,避免组件渲染异常。
内容的提问来源于stack exchange,提问作者Saba S
相关产品推荐
相关产品推荐

