Why does my create-react-app console.log twice?

家住魔仙堡 提交于 2020-06-23 14:53:11

问题


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;

回答1:


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:

  • 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

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.



来源:https://stackoverflow.com/questions/61521734/why-does-my-create-react-app-console-log-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!