首页 > 解决方案 > 尝试运行定制的钩子,使用了这个 api“https://type.fit/api/quotes”。我能够在对象中获得一堆引号,但无法获得引号

问题描述

我是一个新手,在这里我正在尝试定制钩子。我正在使用这个 API “https://type.fit/api/quotes” 我面临的问题是,没有得到任何错误,也没有在我的输出中得到任何引号。请帮助我找出并理解问题所在

function App() {
  const [quote, setQuote]=useState();
  useEffect(() => {
    const fetchQuote =async()=>{
      await fetch("https://type.fit/api/quotes")
        .then(
          (response)=>response.json())
        .then(
          (data)=>{setQuote(data.value)});
          // console.log(text);
      }
    fetchQuote();
  }, [])
  return (
    <div>
      <h1>Random Quotes</h1>
      <p>{quote}</p>
      <button>Click For Random Quotes</button>
    </div>
  );
}

标签: reactjsdebuggingreact-hooksuse-effect

解决方案


响应是一个数组

// 20211109225522
// https://type.fit/api/quotes

[
  {
    "text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "text": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  },
  {
    "text": "A house divided against itself cannot stand.",
    "author": "Abraham Lincoln"
  },
  ...

所以data.value是未定义的,只需存储data在状态中并适当地渲染。

function App() {
  const [quotes, setQuotes] = useState([]);

  useEffect(() => {
    const fetchQuote = async () => {
      await fetch("https://type.fit/api/quotes")
        .then((response) => response.json())
        .then((data) => setQuotes(data));
    };
    fetchQuote();
  }, []);

  return (
    <div>
      <h1>Random Quotes</h1>
      <ul>
        {quotes.map(({ author, text }, index) => (
          <li key={index}>
            "{text}" ~{author}
          </li>
        ))}
      </ul>
      <button>Click For Random Quotes</button>
    </div>
  );
}

编辑 try-to-run-cutomized-hook-used-this-api-https-type-fit-api-quotes-im-a

在此处输入图像描述


推荐阅读