繁体   English   中英

无法在 useEffect 挂钩中访问更新的 state

[英]Can't access updated state inside useEffect hook

我有一个节点服务器,它侦听load video事件,然后发出load事件,以加载视频。

我在客户端内监听这个事件,如下所示:

useEffect(() => {
    socketRef.current = io.connect('/');

    socketRef.current.on("load", () => {
        loadVideo();
    })
}, []);

对于此示例, loadVideo function 仅记录videoID的值,其设置如下:

<input type="text" placeholder="video link" value={videoID} onChange={e => setVideoID(e.target.value)} />

Every time when the loadVideo function gets executed from inside the useEffect, it logs the initial state, which is an empty string, but if I were to call the function from some other function which is not inside a useEffect, then it logs the updated value . 谁能解释这是为什么?

这是因为您的useEffect没有依赖项,这意味着它仅在组件安装时调用。 我会将videoId添加为其依赖项。

只是一个旁注,如果你在这里发布你的loadVideo代码,它不会受到伤害:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM