React中如何处理Props传入数组并完成多轮Axios请求
React评论组件优化:批量获取评论者信息与删除功能实现
修正后的完整代码
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import Typography from '@mui/material/Typography'; export default function Comments(props) { const [commentsWithUsers, setCommentsWithUsers] = useState([]); // 获取评论并批量拉取评论者信息 useEffect(() => { if (!props.post?._id) return; axios.get(`http://localhost:6006/api/v1/posts/${props.post._id}/comments`) .then(res => { const commentList = res.data.data; // 批量请求每个评论的用户信息,合并到评论对象中 return Promise.all( commentList.map(comment => axios.get(`http://localhost:6006/api/v1/users/${comment.user_id}`) .then(userRes => ({ ...comment, user: userRes.data.data })) ) ); }) .then(commentsWithUsersData => { setCommentsWithUsers(commentsWithUsersData); }) .catch(err => console.error('获取评论或用户信息失败:', err)); }, [props.post?._id]); // 删除评论函数 const deleteComment = (commentId) => { axios.delete(`http://localhost:6006/api/v1/comments/${commentId}`) .then(() => { // 删除后更新本地状态,过滤已删除的评论 setCommentsWithUsers(prev => prev.filter(comment => comment._id !== commentId)); }) .catch(err => console.error('删除评论失败:', err)); }; return ( <div> {commentsWithUsers.map(comment => ( <div key={comment._id} style={{ marginBottom: '1rem' }}> <Typography variant="h6"> {comment.user.name}: {comment.text} </Typography> <button onClick={() => deleteComment(comment._id)} style={{ marginTop: '0.5rem', padding: '0.3rem 0.8rem' }} > 删除评论 </button> </div> ))} </div> ); }
关键优化点说明
- 状态重构:把原有的独立
comments和user状态合并为commentsWithUsers,让每条评论对象自带对应用户信息,解决单个user状态无法匹配多条评论的问题。 - 批量请求处理:用
Promise.all配合数组map一次性发起所有评论者的信息请求,全部请求完成后统一更新状态,避免多次触发渲染。 - 依赖修正:将
useEffect依赖设为props.post?._id,确保帖子ID变化时自动重新拉取对应评论;同时增加空值判断,避免未传入帖子时发起无效请求。 - 删除功能实现:新增
deleteComment函数,调用删除接口后直接从本地状态移除对应评论,无需重新拉取全部数据,提升交互效率。 - 渲染逻辑简化:渲染时直接从每条
comment对象读取user.name,无需额外处理状态关联。
内容的提问来源于stack exchange,提问作者airemike
相关产品推荐
相关产品推荐

