【问题标题】:React console.log showing duplicate results in Dev ToolsReact console.log 在开发工具中显示重复的结果
【发布时间】:2022-08-14 17:51:56
【问题描述】:

为什么 React 显示重复的 console.log?我发现要从 index.js 中删除 StrictMode。但是以前没有这样的问题,为什么我要删除 StrictMode 而不是解决问题。还能有什么其他问题?

看截图:https://prnt.sc/HLAmthr9efoB

import React, { useEffect, useState } from \"react\";
import Country from \"../Country/Country.js\";

const gridStyle = {
  display: \"grid\",
  gridTemplateColumns: \"repeat(4, 1fr)\",
  gridGap: \"20px\",
};

const Countries = () => {
  const [countries, setCountries] = useState([]);
  useEffect(() => {
    fetch(\"https://restcountries.com/v3.1/all\")
      .then((res) => res.json())
      .then((data) => setCountries(data));
  }, []);
  console.log(countries);
  return (
    <div className=\"all-countries\">
      <p>{countries.length}</p>
      <div style={gridStyle} className=\"country-container\">
        {countries.map((country) => (
          <Country key={Math.random() * 500000} country={country}></Country>
        ))}
      </div>
    </div>
  );
};

export default Countries;
  • 您的组件可能会被渲染多次。
  • 你能提供一些代码吗?请查看stackoverflow.com/help/minimal-reproducible-example
  • 请提供足够的代码,以便其他人可以更好地理解或重现该问题。
  • 用代码编辑了帖子
  • 这很常见,react 会在每次渲染时调用你的组件(在开发中它会发生两次以确保)因此 console.log() 将被执行多次。

标签: javascript reactjs react-hooks jsx use-state


【解决方案1】:

要解决此问题,您必须在 index.js 中评论 StrictMode

【讨论】:

    【解决方案2】:

    很可能您在触发日志的function 之外编写console.log(),
    所以每次重新渲染组件时都会被触发。

    【讨论】:

    • 不,我在组件函数中使用 console.log。即使在组件之外使用它也能完美显示。
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2022-11-15
    • 2020-02-08
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    相关资源
    最近更新 更多