相关疑难解决方法(0)

this.state 与 useState 的 setTimeout

当我使用类组件时,我有代码:

setTimeout(() => console.log(this.state.count), 5000);
Run Code Online (Sandbox Code Playgroud)

当我使用钩子时:

const [count, setCount] = useState(0);
setTimeout(() => console.log(count), 5000);
Run Code Online (Sandbox Code Playgroud)

如果我触发setTimeout然后count在超时 ( 5000ms)之前将更改为 1 ,类组件将console.log(1)(最新值),并且useStateconsole.log(0)(注册超时时的值)。
为什么会发生这种情况?

javascript reactjs react-hooks

5
推荐指数
2
解决办法
582
查看次数

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

我在尝试 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,就像每次组件渲染到屏幕上一样。但它似乎在增加它,但不是每次都将其打印到控制台。

我在这里错过了什么吗?

javascript reactjs react-component

2
推荐指数
1
解决办法
1871
查看次数