简体   繁体   English

为什么在反应中多次调用api?

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

I have a very basic api and all it does is return the text "Sunny day".我有一个非常基本的 api,它所做的只是返回文本“晴天”。

I create a react project using create react app and try to call the api once then printing result to the console.我使用 create react app 创建了一个反应项目,并尝试调用一次 api,然后将结果打印到控制台。

Here is the react app这是反应应用程序

 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;

The problem is the api is getting called twice on page load问题是 api 在页面加载时被调用了两次

Can anybody explain why?谁能解释为什么?

Generally if you want to execute something once, like fetching something from the api on loading the page, you should use the useEffect hook with an empty dependency array like so:一般来说,如果你想执行一次,比如在加载页面时从 api 获取一些东西,你应该使用带有空依赖数组的useEffect钩子,如下所示:

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

Edit: This might be also caused by <StrictMode> .编辑:这也可能是由<StrictMode>引起的。 It's intended to make React render twice in development mode so that it can give you suggestions on how you can improve your code and hooks usage.它旨在使 React 在开发模式下渲染两次,以便它可以为您提供有关如何改进代码和钩子使用的建议。 That might be why your app is rendering twice!这可能就是您的应用渲染两次的原因!

The reason is because you might have a service worker installed.原因是您可能安装了服务工作者。 try running the program with尝试运行程序
yarn start --no-service-worker or yarn start --no-service-worker
npm start --no-service-worker

The API is being called twice because your app renders two times for some reason.该 API 被调用了两次,因为您的应用程序出于某种原因呈现了两次。 Why does the component render twice is an other question you might find an answer to in this SO thread .为什么组件渲染两次是另一个问题,您可能会在此SO 线程中找到答案。

Since you are calling the endpoint that way every time your component renders an API call will be made.由于每次组件呈现时都会以这种方式调用端点,因此将进行 API 调用。 To avoid that you can add the API call in a useEffect and make it run only the first time your component renders.为避免这种情况,您可以在 useEffect 中添加 API 调用,并使其仅在组件第一次呈现时运行。 ( More on useEffect ) 更多关于 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