简体   繁体   English

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

[英]How to handle loading data using fetch and React Hooks

I am new to React and somewhat new to JavaScript.我是 React 新手,对 JavaScript 有点陌生。 I am doing a practice challenge and trying to determine how to handle useEffect with an asynchronous function so I can use the data later in the code.我正在做一个练习挑战,并试图确定如何使用异步 function 处理useEffect ,以便稍后在代码中使用数据。 Currently my quote variable remains "" , but I'm trying to get it to render an actual quote from the API in the the paragraph with id of text along with author in the author paragraph.目前我的报价变量仍然是"" ,但我试图让它在段落中呈现来自 API 的实际报价,其中包含text id 以及author段落中的作者。 Can someone help?有人可以帮忙吗? Disregard that I use id's repeatedly in the JSX.忽略我在 JSX 中反复使用 id。 That is what the challenge asked for.这就是挑战所要求的。 Thanks.谢谢。

The code is below but here is a link to what I have so far for the challenge within codepen.io: https://codepen.io/malbrecht13/pen/QWdNGYp?editors=0111 .代码在下面,但这里是我迄今为止在 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')
)

Your fetch() headers don't match the $.ajax() headers in the provided solution, so you end up getting a CORS error, preventing the response from being loaded.您的fetch()标头与提供的解决方案中的$.ajax()标头不匹配,因此您最终会收到 CORS 错误,从而阻止加载响应。 You had set Content-Type while they were setting Accept instead.您在他们设置Accept时设置了Content-Type

You should also reconsider the organization of your stateful variables, since you only need to fetch the quotes once and not each time you set the index:您还应该重新考虑有状态变量的组织,因为您只需要获取一次引号,而不是每次设置索引时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM