简体   繁体   English

为什么useEffect里面的console.log会运行两次

[英]why console.log inside the useEffect runs twice

i'm currently working with react project, which gets data from api and show it on the console.我目前正在使用 react 项目,该项目从 api 获取数据并将其显示在控制台上。

although i wrote the console.log() just one time inside the useEffect hooks (with the [articles] dependency ), the web browser's console.log always shows the console.log two times like this: enter image description here虽然我在 useEffect 钩子中只写了一次 console.log()(带有 [articles] 依赖项),但 web 浏览器的 console.log 总是像这样显示 console.log 两次:在此处输入图像描述

but i don't know reason why..但我不知道为什么..

in my thought when the 'articles' state set by first useEffect hook, the second useEffect hook activates and console.log should be run only one time.. but it didn't.在我的想法中,当第一个 useEffect 钩子设置的“文章”state 时,第二个 useEffect 钩子激活并且 console.log 应该只运行一次......但它没有。

here is my code这是我的代码

 const NewsList = () => { const [articles, setArticles] = useState([]); useEffect(()=> { const getData = async () => { const response = await axios.get(`https://newsapi.org/v2/top-headlines?country=kr&apiKey='' `); setArticles(response.data.articles); } getData(); },[]) useEffect(()=> { console.log(articles); },[articles]) return ( <div className="newsListBlock"> <NewsArticle article={article}></NewsArticle> <NewsArticle article={article}></NewsArticle> <NewsArticle article={article}></NewsArticle> <NewsArticle article={article}></NewsArticle> <NewsArticle article={article}></NewsArticle> </div> ); };

The effect is run every time the dependencies change.每次依赖项更改时都会运行效果。

  1. The first value, on the first update of the component, is [] (the initial state).第一个值,在组件的第一次更新时,是[] (初始状态)。
  2. The second value, after the data-getting effect runs, is whatever you get from newsapi.org.在数据获取效果运行之后,第二个值是您从 newsapi.org 获得的任何值。

Additionally, if you're using <StrictMode> and a React development build, certain lifecycles can be invoked twice.此外,如果您使用<StrictMode>和 React 开发构建,则可以调用某些生命周期两次。 See eg this codesandbox ;参见例如 这个代码框 if you remove the <StrictMode> from index.js , you'll see less console.logs.如果你从index.js中删除<StrictMode> ,你会看到更少的 console.logs。

From the official react doc :来自官方反应文档

By using this Hook, you tell React that your component needs to do something after render.通过使用这个 Hook,你告诉 React 你的组件需要在渲染之后做一些事情。

So this useEffect will run once on the first render of the component, and then run a second time due to the use the setArticles function which update articles .所以这个useEffect将在组件的第一次渲染时运行一次,然后由于使用更新articlessetArticles function 而运行第二次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM