【问题标题】:Save a react axios response of a .jpg into state then display that image from state将 .jpg 的 react axios 响应保存到状态,然后从状态显示该图像
【发布时间】:2021-03-08 13:20:13
【问题描述】:

如何直接从任何 .jpg 链接将响应数据保存到状态,然后将该图像加载到 img 标记中。

import { useState, useEffect } from 'react';
import axios from 'axios';

const ProfileImage = () => {

  const [profileImage, setProfileImage] = useState();
  const [loading, setLoading] = useState(true);
  
  const getUserImage = async () => {
    let res = await axios({
      method: 'get',
      url: `https://st.depositphotos.com/1937573/2310/i/600/depositphotos_23101854-stock-photo-handsome-man-outdoor.jpg`
    });
    setProfileImage(res.data);
    setLoading(false);
  }
  
  useEffect(() => {
    getUserImage();  
  }, []);

  return (
      {loading && <div>loading...</div>}
      {!loading && <img src={profileImage} />}
  )
};

export default ProfileImage;

【问题讨论】:

  • 您有什么理由不想将图像网址(不是图像数据)保存在状态并在图像的src 属性中使用它。?相关question
  • 我正在构建一个高度可扩展的社交媒体网站,其中包含动态生成的内容。我用于提要和 cmets 的所有用户图像都是 40x40,我正在尝试将已获取的迷你用户图像存储到全局 redux 中,以避免对我的 aws s3 存储桶进行冗余获取以获取新获取的动态内容。我最终可能只是直接使用链接作为来源。

标签: javascript html reactjs image axios


【解决方案1】:

您需要阅读 get the response as blob。所以使用responseType: "blob", 拥有博客后使用FileReader 将其转换为图像数据。

您的完整代码如下所示。查看工作版本here

import "./styles.css";
import axios from "axios";
import { useEffect, useState } from "react";

export default function App() {
  const [profileImage, setProfileImage] = useState();
  const [loading, setLoading] = useState(true);

  const getUserImage = async () => {
    let res = await axios({
      method: "get",
      responseType: "blob",
      url: `https://st.depositphotos.com/1937573/2310/i/600/depositphotos_23101854-stock-photo-handsome-man-outdoor.jpg`
    });
    let reader = new window.FileReader();
    reader.readAsDataURL(res.data);
    reader.onload = function () {
      let imageDataUrl = reader.result;
      //console.log(imageDataUrl);
      setProfileImage(imageDataUrl);
      setLoading(false);
    };
  };

  useEffect(() => {
    getUserImage();
  }, []);

  return (
    <>
      {loading && <div>loading...</div>}
      {!loading && <img width="100" alt="" src={profileImage} />}
    </>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多