如何将State中的UserID传入GET请求URL以获取指定用户帖子
问题:如何将userId传入axios URL获取特定用户帖子
我已将用户信息存储在State中:
const [users, setUsers] = useState([])
想把userId传入axios的URL来获取特定用户的帖子,但当前尝试存在问题,需要解决。以下是我的相关代码:
Dashboard组件代码
const Dashboard = () => { const getPost = () => { axios.get(`/api/getpost/${users._id}`, // 我想在此URL中传入用户ID,替换${users._id} { withCredentials: 'true', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then((response) => { setUposts(response.data) }) } useEffect(() => { getPost() }, []) return ( // something here ) }
UserSchema定义
const userSchema = new Schema({ username: { type: String, required: true }, roles: { User: { type: Number, default: 2001 }, Mentor: Number, Admin: Number }, password: { type: String, required: true }, userID: { type: String, required: true }, Profile: { type: mongoose.Schema.Types.ObjectId, ref: "profile", }, refreshToken: String }); const User = mongoose.model('user', userSchema); module.exports = User;
获取用户帖子的API
router.get('/getpost/:id/', (req, res) => { const id = req.params.id; // const profID = req.params.prof_id; Userpost.find({User:id}).populate('User', {password: 0}).populate('Profile').exec((err,docs) => { if(err) throw(err); res.json(docs); }) });
setUsers实现代码
const getUser = () => { axios.get('/api/users', { withCredentials: 'true', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then((response) => { setUsers(response.data) }) }; useEffect(() => { getUser() }, [])
问题分析与修复方案
1. 修正State的类型与取值逻辑
你把users初始化为数组[],但users._id是错误的——数组没有_id属性。首先要明确/api/users返回的是单个用户对象还是用户数组:
- 如果返回单个当前登录用户:把State初始值改为对象
{},并在获取ID前判断用户是否加载完成:const [users, setUsers] = useState({}) const getPost = () => { // 先判断用户是否存在,避免空值错误 if (!users._id && !users.userID) return; // 根据API需要的ID类型选择:是用MongoDB的_id还是自定义的userID const userId = users.userID || users._id; axios.get(`/api/getpost/${userId}`, { withCredentials: 'true', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then((response) => { setUposts(response.data) }) } - 如果返回用户数组:需要指定要获取哪个用户的帖子,比如取第一个用户:
const getPost = () => { const targetUser = users[0]; if (!targetUser) return; const userId = targetUser.userID || targetUser._id; // 后续axios请求逻辑同上 }
2. 确保API与数据库字段匹配
查看Userpost模型,确认User字段存储的是用户的_id(MongoDB自动生成)还是自定义的userID:
- 如果
Userpost的User存的是自定义userID,则前端传入users.userID; - 如果存的是MongoDB的
_id,则传入users._id,保证前后端字段一致。
3. 修复useEffect的依赖与加载顺序
当前getPost在组件挂载时立即执行,但此时users可能还没从后端获取到,导致传入的ID为空。需要把users加入useEffect的依赖数组,确保用户数据加载后再调用getPost:
useEffect(() => { getPost() }, [users]) // 当users数据更新时,重新调用getPost获取帖子
4. 可选:添加加载状态处理
为了避免用户看到空白或错误,可以添加加载状态提示:
const [isLoading, setIsLoading] = useState(true); const getUser = () => { axios.get('/api/users', { ... }) .then((response) => { setUsers(response.data); setIsLoading(false); }) .catch(() => { setIsLoading(false); console.error("获取用户信息失败"); }); }; // 在组件返回时判断 if (isLoading) return <div>加载中...</div>;
内容的提问来源于stack exchange,提问作者SwiftDev
相关产品推荐
相关产品推荐

