如何使用来自API的图像文件?

huangapple go评论63阅读模式
英文:

How to use a image file from a API?

问题

I'm doing a NFT page and I'm trying to use some img from an api but it seems it returns the file image itself so how can I transform or get that path to give me the actual img.

Here is my code:

const [userData, setUserData] = useState([])

async function fetchData() {
    const { data } = await axios.get('https://us-central1-nft-cloud-functions.cloudfunctions.net/hotCollections')
    setUserData(data) 
    console.log(data)
} 

useEffect(() => {
    fetchData()
}, [])

I'm searching but I havent found a solution yet.

英文:

I'm doing a NFT page and I'm trying to use some img from an api but it seems it returns the file image itself so how can I transform or get that path to give me the actual img.

Here is my code:

const [userData, setUserData] = useState([])

async function fetchData() {
    const { data } = await axios.get('https://us-central1-nft-cloud-functions.cloudfunctions.net/hotCollections')
    setUserData(data) 
    console.log(data)
} 

useEffect(() => {
    fetchData()
}, [])

I'm searching but I havent found a solution yet.

答案1

得分: 0

以下是翻译好的内容:

看起来你接收到的数据是 <img> 元素的确切 src 值。例如,当我访问你的 URL 时,返回的数组中的第一个对象是:

{
  "id": 1,
  "title": "抽象",
  "authorImage": "https://nft-place.web.app/static/media/author-1.04ee784f53cbe427d362.jpg",
  "nftImage": "https://nft-place.web.app/static/media/coll-1.b8f9d867e8ed59ee7fa7.jpg",
  "nftId": 39924405,
  "authorId": 83937449,
  "code": 192
}

这些图像值只是 URL(或在某些情况下是 base64 图像数据,但对于浏览器来说几乎没有区别),你可以在你的标记中使用。例如:

{
  userData.map(user => (
    <div key={user.id}>
      <h1>{user.title}</h1>
      <img src={user.authorImage} alt={user.title} />
    </div>
  ))
}

示例链接

英文:

It looks like the data you're receiving is the exact src value for an &lt;img&gt; element. For example, when I go to your URL, the first object in the returned array is:

{
  &quot;id&quot;: 1,
  &quot;title&quot;: &quot;Abstraction&quot;,
  &quot;authorImage&quot;: &quot;https://nft-place.web.app/static/media/author-1.04ee784f53cbe427d362.jpg&quot;,
  &quot;nftImage&quot;: &quot;https://nft-place.web.app/static/media/coll-1.b8f9d867e8ed59ee7fa7.jpg&quot;,
  &quot;nftId&quot;: 39924405,
  &quot;authorId&quot;: 83937449,
  &quot;code&quot;: 192
}

Those image values are simply URLs (or in some cases base64 image data, but to the browser it makes little difference), which you can use in your markup. For example:

&lt;&gt;
{
  userData.map(user =&gt; (
    &lt;div key={user.id}&gt;
      &lt;h1&gt;{user.title}&lt;/h1&gt;
      &lt;img src={user.authorImage} alt={user.title} /&gt;
    &lt;/div&gt;
  ))
}
&lt;/&gt;

huangapple
  • 本文由 发表于 2023年4月13日 20:01:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定