如何显示从 axios 请求(React)返回的图像? [英] How to display an image which comes back from an axios request (React)?

查看:44
本文介绍了如何显示从 axios 请求(React)返回的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React 开发一个谷歌地图项目.我为 onClick 处理程序分配了以下方法:

I'm working on a google maps project with React. I assign an onClick handler the following method:

  getStreetView(lat,lng){
    let url = `https://maps.googleapis.com/maps/api/streetview?size=600x300&location=${lat},${lng}&heading=151.78&pitch=-0.76&key=MYAPIKEY`
    axios.get(url).then(response=>this.setState({image:response.config.url}));
  }

state = { image: null } 然后被分配了 url,我稍后将其传递给一个图像标记给一个子组件,例如 <img src={props.图片} alt='street view'/>.一切都像魅力一样,但是我遇到了各种其他解决方案,例如:

the state = { image: null } is then beeing assigned the url which I later pass on to an image tag to a child component such as <img src={props.image} alt='street view'/>. Everything works like a charm, however I have come across various other solutions such:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

来自 axios 文档中的 b4dnewz.但是,我找不到如何在具有该响应类型的子组件中显示图像的合理方法.我的问题是,我的方法有效吗?有什么理由让我不应该那样使用它吗?

from b4dnewz from the axios documentation. However I can't find a reasonable approach how to display the image in child component with that response type. My question is, is my approach valid? Is there any reasons why I shouldn't be using it like that?

推荐答案

如果您是从 api 获取图像 url,那么您的第一种方法是正确的方法,但是

If you are getting the image url from api, then your first method is the right approach, but the

Buffer.from(response.data, 'binary').toString('base64'))

当图像本身作为二进制文件从服务器接收时使用,该二进制文件被转换为 base 64 并提供给

method is used when the image itself is received from server as a binary which is converted to base 64 and given to <img>

这篇关于如何显示从 axios 请求(React)返回的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆