【问题标题】:Why does my create-react-app console.log twice?为什么我的 create-react-app console.log 两次?
【发布时间】:2020-08-14 17:14:11
【问题描述】:

我只是使用 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;

【问题讨论】:

标签: reactjs create-react-app use-state


【解决方案1】:

这是故意的,它是React.StrictMode 的一部分(特别是detect unexpected side effects):

严格模式无法自动为您检测副作用,但它 可以通过使它们更具确定性来帮助您发现它们。 这是通过有意双重调用以下函数来完成的:

  • 类组件constructorrendershouldComponentUpdate方法
  • 类组件静态getDerivedStateFromProps方法
  • 函数组件体
  • 状态更新函数(setState 的第一个参数)
  • 函数传递给useStateuseMemouseReducer

如果您从 index.js 中删除 StrictMode 元素,您将看到输出仅记录一次:

ReactDOM.render(<App />, document.getElementById('root'));

请注意,在严格模式下,这只发生在开发中,而不是在生产中。

【讨论】:

猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2019-09-19
  • 2020-11-17
相关资源
最近更新 更多