为什么React Component渲染计数器增加2? [英] Why is React Component render counter getting incremented by 2?

查看:44
本文介绍了为什么React Component渲染计数器增加2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试React组件时遇到了这个问题.我有一个组件:

I came across this when I was experimenting with react components. I have a component:

window.renderCount=1;

export function Soundscapes() {

    const soundscape = useSelector((s) => s.tasks.soundscape);
    const dispatch = useDispatch();
   
    const [soundscapeAudioElement, setSoundscapeAudioElement] = useState(undefined);
    useEffect(()=>{
        console.log('state just changed to: ', soundscapeAudioElement )
    },[soundscapeAudioElement])

    
    console.log(window.renderCount);
    window.renderCount=window.renderCount+1;

    return (<SomeJSXUnrelatedToQuestion/>)
}

在控制台中,我注意到在随后的重新渲染中,日志为 1、3、5、7、9 .我希望它每次像 1,2,3,4,5 一样在屏幕上每次递增1 时打印 renderCount .组件已呈现到屏幕.但这似乎是在增加它,但并非每次都将其打印到控制台.

In the console, I noticed that the logs are 1,3,5,7,9 on subsequent re-rendering. I expected it to print renderCount everytime it is incremented by 1 on the screen like 1,2,3,4,5, each time the component got rendered to screen. But it seems to be incrementing it, but not printing it to console everytime.

我在这里想念东西吗?

推荐答案

您可能已启用 StrictMode . StrictMode 将故意两次调用"render",和其他一些生命周期方法来检测副作用.严格模式检查仅在开发模式下运行;它们不会影响生产.检查以下代码段.另外,请注意,我已经使用了React development CDN.

You probably have StrictMode on. StrictMode will intentionally double invoke "render" and some other lifecycle methods to detect side-effects. Strict mode checks are run in development mode only; they do not impact the production build. Check the below snippet. Also, note that I have used React development CDNs.

function App() {
    const [foo, setFoo] = React.useState(false)
    const counter = React.useRef(0)
    console.log(counter.current++)
    return (
      <button onClick={() => setFoo(f => !f)} > Click </button>
     )
}

ReactDOM.render(<React.StrictMode><App /></React.StrictMode>, document.getElementById('mydiv'))

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<body>
<div id="mydiv"></div>
</body>

这篇关于为什么React Component渲染计数器增加2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆