【发布时间】: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