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

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

问题描述

我正在使用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,然后我将该URL传递给子组件(例如<img src={props.image} 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并提供给<img>

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请求返回的图像(反应)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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