我刚开始创建了一个新的create-react-app项目,并注意到React在渲染组件两次!我的package.json中的React版本是"react": "^16.13.1"
import React, { useRef } from "react";
const App = () => {
const renders = useRef(0);
console.log("renders: ", renders.current++);
return (
<div>
Hello
</div>
);
};
这将在首次呈现时产生以下效果:
renders: 0
renders: 0
现在如果我添加一个按钮来增加状态,每次状态改变也会产生两个额外的渲染:
import React, { useRef } from "react";
const App = () => {
const [count, setCount] = useState(0);
const renders = useRef(0);
console.log("renders: ", renders.current++);
return (
<div>
<button onClick={() => setCount(count + 1)}>increment</button>
<div>count: {count}</div>
</div>
);
};
这将导致:
//--- initial render
renders: 0
renders: 0
//--- first click
renders: 1
renders: 2
//--- second click
renders: 3
renders: 4
//--- third click
renders: 5
renders: 6
这是正常现象还是最新版本的React中存在的一个bug?