我只是使用create-react- app设置制作一个简单的配方获取应用程序,但是当我尝试记录响应时,它记录了两次。我向后移动并删除了代码,直到它停止发生,并且无论出于何种原因,当我使用状态钩子时它都开始了:
import React, { useState } from 'react'; import './App.css'; function App() { const APP_ID = '092fa53f'; const APP_KEY = '6fcf8c591c129cc3d01aefbda0d8a4d8'; const recipe_url = `https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`; const [recipes, setRecipes] = useState(0); return ( <div className="App"> {console.log('test')} </div> ); } export default App;
这是有目的的,它是React.StrictMode(专门用于检测意外副作用)的一部分:
React.StrictMode
严格模式无法自动为您检测副作用,但可以通过使其更具确定性来帮助您发现它们。这是通过有意地双重调用以下功能来完成的: 类成分constructor,render和shouldComponentUpdate方法 类组件静态getDerivedStateFromProps方法 功能组件主体 状态更新器功能(的第一个参数setState) 函数传递给useState,useMemo或useReducer
严格模式无法自动为您检测副作用,但可以通过使其更具确定性来帮助您发现它们。这是通过有意地双重调用以下功能来完成的:
constructor
render
shouldComponentUpdate
getDerivedStateFromProps
setState
useState
useMemo
useReducer
如果StrictMode从中删除元素index.js,您将看到输出仅记录一次:
StrictMode
index.js
ReactDOM.render(<App />, document.getElementById('root'));
请注意,在严格模式下,这仅在 开发中 发生,而不在生产中发生。