简体   繁体   English

将 a.jpg 的反应 axios 响应保存到 state 然后显示来自 state 的图像

[英]Save a react axios response of a .jpg into state then display that image from state

How can I save the response data into state first directly from any.jpg link then load that image into the img tag.如何首先直接从 any.jpg 链接将响应数据保存到 state 中,然后将该图像加载到 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;

You need to read get the response as blob .您需要阅读 get the response as blob So use responseType: "blob", Once you have the blog use FileReader to convert it to image data.所以使用responseType: "blob",一旦你有了博客,使用FileReader将其转换为图像数据。

Your full code will look like below.您的完整代码如下所示。 See the working version 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} />}
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM