You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中props未传递就发起API请求的问题解决

解决方案

你的问题核心是useEffect的执行时机和依赖数组配置不对:

  • 空依赖数组的useEffect只会在组件挂载时执行一次,这时候组件可能还没接收到从Link传递过来的props,所以id是undefined。
  • 另外你的代码里模板字符串少了结尾的反引号,这也是潜在bug。

直接按下面的方式修改代码:

const user = useContext(UserContext);
const id = props.followerId;

useEffect(() => {
    // 只有当id存在时才发起请求,避免无效调用
    if (!id) return;

    axios
        .get(`http://localhost:3000/users/followers/${id}`)
        .then((res) => {
            if (res.status === 200) {
                user.setFollower(res.data);
            }
        })
        .catch((err) => {
            console.log(err);
        });
}, [id]); // 把id加入依赖数组,当id变化时自动触发useEffect

关键修改点说明:

  • 依赖数组添加id:当props传递的followerId更新时,useEffect会重新执行,此时id已经是正确的值。
  • 增加id存在性判断:即使id暂时为undefined,也不会发起无效请求,避免控制台报错。
  • 修复模板字符串语法错误:补上结尾的反引号,保证请求地址正确。

内容的提问来源于stack exchange,提问作者darkshadowtrail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:27:18