簡體   English   中英

為什么在反應中多次調用api?

[英]Why is fetch calling api multiple times in react?

我有一個非常基本的 api,它所做的只是返回文本“晴天”。

我使用 create react app 創建了一個反應項目,並嘗試調用一次 api,然后將結果打印到控制台。

這是反應應用程序

 import logo from './logo.svg'; import './App.css'; function App() { fetch('https://localhost:44386/weatherforecast') .then(response => response.text()) .then(data => console.log(data)); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;

問題是 api 在頁面加載時被調用了兩次

誰能解釋為什么?

一般來說,如果你想執行一次,比如在加載頁面時從 api 獲取一些東西,你應該使用帶有空依賴數組的useEffect鈎子,如下所示:

React.useEffect(
 () => {
         fetch('https://localhost:44386/weatherforecast')
         .then(response => response.text())
         .then(data => console.log(data));
 }, []) // <--- empty dependency array

編輯:這也可能是由<StrictMode>引起的。 它旨在使 React 在開發模式下渲染兩次,以便它可以為您提供有關如何改進代碼和鈎子使用的建議。 這可能就是您的應用渲染兩次的原因!

原因是您可能安裝了服務工作者。 嘗試運行程序
yarn start --no-service-worker
npm start --no-service-worker

該 API 被調用了兩次,因為您的應用程序出於某種原因呈現了兩次。 為什么組件渲染兩次是另一個問題,您可能會在此SO 線程中找到答案。

由於每次組件呈現時都會以這種方式調用端點,因此將進行 API 調用。 為避免這種情況,您可以在 useEffect 中添加 API 調用,並使其僅在組件第一次呈現時運行。 更多關於 useEffect

useEffect(() => {
  fetch('https://localhost:44386/weatherforecast')
    .then(response => response.text())
    .then(data => console.log(data));
}, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM