React Hooks: state not updating when called inside Socket.io handler

孤街浪徒 提交于 2021-01-29 10:26:43

问题


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

...

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

...


useEffect(() => {
    console.log(questionIndex);
}, [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?


回答1:


It looks like you open new socket every render and never disconnect it. Try to place socket.on inside useEffect and the return value of that useEffect will be function that disconnect the socket.

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

  return () => socket.disconnect();
}, [questionIndex]);```



回答2:


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

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




回答3:


I was also facing this issue. Actually, we should not rely on values from state while updation.

right way to do this is

setQuestionIndex(QuestionIndex=>QuestioIndex+1)


来源:https://stackoverflow.com/questions/63096828/react-hooks-state-not-updating-when-called-inside-socket-io-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!