【问题标题】:React.js display image from saved api responseReact.js 从保存的 api 响应中显示图像
【发布时间】:2021-04-28 17:52:32
【问题描述】:

所以我想从 API 中获取一个简单的图像。我的目标是显示来自 API 的随机图像。现在它说“数据”没有定义。我不知道为什么会这样,因为我的 console.logs 在尝试在页面上显示之前就已经工作了。

这是我的 App.js

import React,{useEffect, useState} from 'react';
import Dog from './doggo';

//Main component
function App() {

  const [dogs, setDog] = useState();

  useEffect(() => {
      getDog();
  }, []);
  //Function to get data
  const getDog = async () => {
      //Fetch from url
      const response = await fetch("https://dog.ceo/api/breeds/image/random");
      //Store answer in data
      const data = await response.json();
      //Place data.message in setDog
      setDog(data.message);

      console.log(data.status);
      //data.message contains image url
      console.log(data.message);
  };
  return(
      <div>
          <h1>Press button to see your future dog!</h1>
          <button type="submit">See your dog!</button>
          <Dog
            image={data.message}
          />
      </div>
  );
};

export default App;

【问题讨论】:

  • 变量data 在getDog 函数之外不可用,您可能打算使用dogs 状态。

标签: javascript reactjs api fetch


【解决方案1】:

我重新格式化了你的代码以解决一些问题。

正如其他评论者所说,data 超出了您尝试访问的范围。 (它仅在 getDog() 函数内部可用。)

export default function App() {
  const [dog, setDog] = useState();

  const getDog = async () => {
    const response = await fetch("https://dog.ceo/api/breeds/image/random");
    const data = await response.json();
    setDog(data.message);
  };
  
  return (
    <div>
      <h1>Press button to see your future dog!</h1>
      <button
        onClick={() => {
          getDog();
        }}
      >
        See your dog!
      </button>
      {dog ? <Dog image={dog} /> : null}
    </div>
  );
}

Working Codepen

【讨论】:

    【解决方案2】:

    在&lt;Dog image={data.message}/&gt; 中使用{dogs} 而不是{data.message} 数据是仅用于getDog() 函数的变量。

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 2019-10-05
      • 2021-10-03
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多