[英]Why does my create-react-app console.log twice?
I'm just making a simple recipe fetching app using the create-react-app setup, but when I tried logging the response it logged it twice.我只是使用 create-react-app 设置制作了一个简单的配方获取应用程序,但是当我尝试记录响应时,它记录了两次。 I went backwards and deleted code until it stopped happening and for whatever reason it starts when I use the state hook:
我倒退并删除了代码,直到它停止发生,无论出于何种原因,当我使用 state 挂钩时它开始:
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;
This is on purpose, it's part of React.StrictMode
(specifically to detect unexpected side effects ):这是故意的,它是
React.StrictMode
的一部分(专门用于检测意外的副作用):
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic.
严格模式不能自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们。 This is done by intentionally double-invoking the following functions:
这是通过有意双重调用以下函数来完成的:
- Class component
constructor
,render
, andshouldComponentUpdate
methodsClass 组件
constructor
、render
和shouldComponentUpdate
方法- Class component static
getDerivedStateFromProps
methodClass 组件 static
getDerivedStateFromProps
方法- Function component bodies
Function 组件体
- State updater functions (the first argument to
setState
)State 更新函数(
setState
的第一个参数)- Functions passed to
useState
,useMemo
, oruseReducer
传递给
useState
、useMemo
或useReducer
的函数
If you remove the StrictMode
element from index.js
, you'll see the output only gets logged once:如果您从
index.js
中删除StrictMode
元素,您将看到 output 只记录一次:
ReactDOM.render(<App />, document.getElementById('root'));
Note that in strict mode this only happens in development , not in production.请注意,在严格模式下,这只发生在开发中,而不是生产中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.