为什么 React 组件渲染计数器会增加 2?

pg0*_*g07 2 javascript reactjs react-component

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

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/>)
}

Run Code Online (Sandbox Code Playgroud)

在控制台中,我注意到日志正在1,3,5,7,9随后重新渲染。renderCount我希望它每次在屏幕上增加 1 时都会打印出来1,2,3,4,5,就像每次组件渲染到屏幕上一样。但它似乎在增加它,但不是每次都将其打印到控制台。

我在这里错过了什么吗?

Aje*_*hah 10

你可能已经StrictMode上了。StrictMode将故意双重调用“render”和其他一些生命周期方法来检测副作用。严格模式检查仅在开发模式下运行;它们不会影响生产构建。检查下面的代码片段。另请注意,我使用了 React开发CDN。

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'))
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)