How to display an image which comes back from an axios request (React)?

和自甴很熟 提交于 2019-12-11 04:28:14

问题


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}));
  }

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'))
}

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?


回答1:


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'))

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



来源:https://stackoverflow.com/questions/50772724/how-to-display-an-image-which-comes-back-from-an-axios-request-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!