【问题标题】:React : How to use the result of an API call, in my JSX? (scope problem)React:如何在我的 JSX 中使用 API 调用的结果? (范围问题)
【发布时间】:2021-12-21 07:58:57
【问题描述】:

我正在尝试使用我的 API 调用(响应)的结果在我的 JSX 中以 src 级别显示它。

但由于范围,我无权访问“响应”。我尝试将响应声明为全局范围内的空变量,然后在我的 useEffect 中分配它,但它不起作用。

useEffect(() => {
    const toFetchProfilPicture = async () => {
      try {       
        const response = await axios.get(
        `http://localhost:4200/api/user/image/${JSON.parse(localStorage.getItem("user")).user_id}`
          );
      } catch (err) {
        throw err;
      }
    };
    toFetchProfilPicture();
  }, []);


  return (
    <div className="modal">
      <form className="modal__infos" onSubmit={saveChange}>
        <div className="modal__photo"> 
          <img src={response.data[0]} alt="profile_picture" />
        </div>
      </form>
    </div>
  );
};

我无法使用函数在全局范围内进行“响应”,但我想不这样做。

如何在我的 JSX 中使用“响应”?

【问题讨论】:

    标签: reactjs use-effect


    【解决方案1】:

    您应该使用包含字符串(图像 URL)的状态变量:

    const [imgSrc, setImgSrc] = useState('');
    
    useEffect(() => {
        const toFetchProfilPicture = async () => {
          try {       
            const { data } = await axios.get(
            `http://localhost:4200/api/user/image/${JSON.parse(localStorage.getItem("user")).user_id}`
              );
    
              setImgSrc(data[0])
          } catch (err) {
            throw err;
          }
        };
        toFetchProfilPicture();
      }, []);
    
    
      return (
        <div className="modal">
          <form className="modal__infos" onSubmit={saveChange}>
            <div className="modal__photo"> 
              <img src={imgSrc} alt="profile_picture" />
            </div>
          </form>
        </div>
      );
    };
    

    【讨论】:

    • 天哪,这太明显了......非常感谢,它有效!
    猜你喜欢
    • 2017-07-27
    • 2023-03-27
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2017-09-27
    • 2020-09-11
    • 2023-01-21
    • 2017-03-16
    相关资源
    最近更新 更多