React Hooks:在 Socket.io 处理程序中调用时状态不会更新 [英] React Hooks: state not updating when called inside Socket.io handler

查看:80
本文介绍了React Hooks:在 Socket.io 处理程序中调用时状态不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const [questionIndex, setQuestionIndex] = useState(0);

...

socket.on('next', () => {
      console.log('hey')
      setQuestionIndex(questionIndex + 1);
});

...


useEffect(() => {
    console.log(questionIndex);
}, [questionIndex]);

我有一个使用 Socket.io 连接到 websocket 的页面.当我从套接字收到下一个"消息时,我试图更新我的 questionIndex 状态变量的值.我似乎收到了消息,因为打印了嘿",但 questionIndex 仅在第一个嘿"之后更新.之后,嘿被打印,但 questionIndex 不是(我使用 useEffect 在更新时打印 questionIndex).大家有没有看错?

I have a page that connects to a websocket using Socket.io. I am attempting to update the value of my questionIndex state variable when I receive a 'next' message from the socket. I seem to be receiving the message because 'hey' is printed, but questionIndex only updates after the first 'hey'. Afterwards, hey is printed, but questionIndex is not (I use the useEffect to print questionIndex when it is updated). Do you guys see anything wrong?

推荐答案

对于那些想知道的人来说,看起来 socket.on('next') 函数处理程序每​​次都使用 questionIndex 的原始值(0).似乎函数处理程序在绑定时编译了这个变量,而不是在运行时读取它.不确定它在文档中的哪个位置指定了这种行为.

For those wondering, it looks like the socket.on('next') function handler was using the original value of questionIndex (which was 0) every time. It seems like the function handler compiled this variable when it was bound rather than reading it at runtime. Not sure where in the documentation it specifies this behavior.

我的解决方案是这样更改函数处理程序:

My solution was to change the function handler as such:

socket.on('next', (newIndex) => {
      console.log('hey')
      setQuestionIndex(newIndex);
});

这通过提供将 questionIndex 设置为的值来解决问题(而不是在收到下一个"事件时读取它).

This solves the problem by providing the value to set questionIndex to (rather than reading it upon receiving a 'next' event).

这篇关于React Hooks:在 Socket.io 处理程序中调用时状态不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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