![](/img/trans.png)
[英]Graphql subscriptions inside a useEffect hook doesn't access latest 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.