为什么我的create-react-app console.log两次? [英] Why does my create-react-app console.log twice?
问题描述
我只是使用create-react-app设置制作一个简单的食谱获取应用,但是当我尝试记录响应时,它记录了两次。我向后删除了代码,直到它停止发生,并且无论使用状态钩子是什么原因开始,它都会停止:
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. I went backwards and deleted code until it stopped happening and for whatever reason it starts when I use the state hook:
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
(特别是检测意外的副作用):
This is on purpose, it's part of React.StrictMode
(specifically to detect unexpected side effects):
严格模式无法自动为您检测副作用,但是
可以通过使它们更具确定性来帮助您发现它们。
这是通过有意重复调用以下函数来完成的:
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:
- 类组件
构造函数
,渲染
和shouldComponentUpdate
方法 - 类组件静态
getDerivedStateFromProps
方法 - 功能组件主体
- 状态更新程序功能(<$的第一个参数c $ c> setState )
- 传递给
useState
,useMemo
或useReducer
- Class component
constructor
,render
, andshouldComponentUpdate
methods - Class component static
getDerivedStateFromProps
method - Function component bodies
- State updater functions (the first argument to
setState
) - Functions passed to
useState
,useMemo
, oruseReducer
如果从 index.js
中删除 StrictMode
元素,您将看到输出仅记录一次:
If you remove the StrictMode
element from index.js
, you'll see the output only gets logged once:
ReactDOM.render(<App />, document.getElementById('root'));
请注意,在严格模式下,这仅发生在开发中,而不是在生产中
Note that in strict mode this only happens in development, not in production.
这篇关于为什么我的create-react-app console.log两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!