我试图跟踪react组件被渲染的次数。但是,似乎renderCounter每次都增加2。
为什么会这样?我知道使用全局变量是一种不好的做法,但是我对这种情况发生的原因很感兴趣。
https://codesandbox.io/s/rendercounter-does-not-increment-correctly-093ok?file=/src/App.js
let renderCounter = 1;
function App() {
const [i, inc] = useReducer((_) => _ + 1, 1);
// render
console.log(JSON.stringify(i), "th click");
console.log("renderCounter", JSON.stringify(renderCounter));
renderCounter = renderCounter + 1;
return (
<div>
<button onClick={inc}>increment</button>
</div>
);
}
export default App;
是的,react render将为您执行两次。为什么-因为你的应用程序包在React.StrictMode成分index.js默认情况下,为什么/什么-有大量的资源覆盖它已经,所以让我只提这一个例- https://medium.com/@ andreasheissenberger / react-components-render-twice-any-to-fixedthis-91cf23961625但让我在这里提一下-如果在生产模式下构建,则不会发生
更新
现在它变得非常有趣,我有点不喜欢React开发人员所做的事情。因此,以上所有内容都是有效的,是的,但正如对本帖子的评论所建议的那样-为什么然后我们没有两次看到console.log消息?正因为如此-https : //github.com/facebook/react/pull/18547 React开发人员只是禁用了控制台日志进行第二次渲染。因此,要查看实际行为(每次应记录2次),您需要使用控制台日志,我做了些什么-将其包装在setTimeout
:
setTimeout(() => console.log(...))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句