如何使用 fetch 和 React Hooks 处理加载数据

How to handle loading data using fetch and React Hooks

我是 React 的新手,对 JavaScript 有点陌生。我正在做一个练习挑战,并试图确定如何使用异步函数处理 useEffect,以便稍后在代码中使用数据。目前,我的引用变量仍然是 "",但我试图让它在 ID 为 text 的段落中呈现来自 API 的实际引用以及 [=] 中的作者14=]段。有人可以帮忙吗?忽略我在 JSX 中重复使用 id。这就是挑战所要求的。谢谢。

代码在下面,但这里是 link 到目前为止我在 codepen.io 中的挑战:https://codepen.io/malbrecht13/pen/QWdNGYp?editors=0111.

const App = () => {
  const [quote, setQuote] = React.useState('');
  const [author, setAuthor] = React.useState('');
  const [quoteNum, setQuoteNum] = React.useState(0);
  
  
  React.useEffect(() => {
    async function getQuotes() {
    const data = await fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const json = await data.json();
    setQuote(json.quotes[quoteNum].quote);
    setAuthor(json.quotes[quoteNum].author);
    setQuoteNum(quoteNum + 1);
  }
    getQuotes();
  }, []);
  
    return (
    <div id="quote-box">
      <p id="text">{quote}</p>
      <p id="author">{author}</p>
      <a id="tweet-quote" href="twitter.com/intent/tweet">Tweet Quote</a>
      <button id="new-quote" >New Quote</button>
    </div>
  )
}

ReactDOM.render(
  <App/>,
  document.getElementById('root')
)

您的 fetch() headers 与提供的解决方案中的 $.ajax() headers 不匹配,因此您最终会收到 CORS 错误,从而阻止响应加载。你设置了 Content-Type 而他们却设置了 Accept

您还应该重新考虑有状态变量的组织,因为您只需要获取一次引号而不是每次设置索引时:

const App = () => {
  const [quotes, setQuotes] = useState();
  const [index, setIndex] = useState(0);
  
  useEffect(() => {
    async function getQuotes() {
      const response = await fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', {
        headers: {
          'Accept': 'application/json'
        }
      });
      const data = await response.json();
      setQuotes(data.quotes);
    }

    getQuotes();
  }, []);

  if (!quotes) return (
    <div id="quote-box">
      <p id="text">Loading...</p>
    </div>
  );

  const { quote, author } = quotes[index];
  const setNext = () => setIndex((index + 1) % quotes.length);

  return (
    <div id="quote-box">
      <p id="text">{quote}</p>
      <p id="author">{author}</p>
      <a id="tweet-quote" href="twitter.com/intent/tweet">Tweet Quote</a>
      <button id="new-quote" onClick={setNext}>New Quote</button>
    </div>
  );
}