为什么我的 create-react-app console.log 两次?
Why does my create-react-app console.log twice?
我只是使用 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
(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:
- Class component
constructor
, render
, and shouldComponentUpdate
methods
- Class component static
getDerivedStateFromProps
method
- Function component bodies
- State updater functions (the first argument to
setState
)
- Functions passed to
useState
, useMemo
, or useReducer
如果从 index.js
中删除 StrictMode
元素,您将看到输出仅记录一次:
ReactDOM.render(<App />, document.getElementById('root'));
请注意,在严格模式下,这仅发生在开发中,而不发生在生产中。
我只是使用 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
(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:
- 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
元素,您将看到输出仅记录一次:
ReactDOM.render(<App />, document.getElementById('root'));
请注意,在严格模式下,这仅发生在开发中,而不发生在生产中。