反应状态未使用 socket.io 更新 [英] React State is not updated with socket.io

查看:37
本文介绍了反应状态未使用 socket.io 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次加载页面时,我需要获取所有信息,这就是为什么我要调用获取请求并将结果设置为状态 [singleCall 函数执行该工作]除此之外,我正在使用 socket.io 连接 websocket 并监听两个事件(odds_insert_one_two、odds_update_one_two),当我收到通知事件时,我必须检查以前的状态并修改一些内容并更新状态,而无需再次调用获取请求.但是之前的状态仍然是 [] (Initial).如何获得更新的状态?

When page loaded first time, I need to get all information, that is why I am calling a fetch request and set results into State [singleCall function doing that work] Along with that, I am connecting websocket using socket.io and listening to two events (odds_insert_one_two, odds_update_one_two), When I got notify event, I have to check with previous state and modify some content and update the state without calling again fetch request. But that previous state is still [] (Initial). How to get that updated state?

片段

  const [leagues, setLeagues] = useState([]);
  
  const singleCall = (page = 1, params=null) => {

    let path = `${apiPath.getLeaguesMatches}`;
    Helper.getData({path, page, params, session}).then(response => {
      if(response) {
        setLeagues(response.results);
      } else {
        toast("Something went wrong, please try again");
      }
    }).catch(err => {
      console.log(err); 
    })
  };

  const updateData = (record) => {

    for(const data of record) {
      var {matchId, pivotType, rateOver, rateUnder, rateEqual} = data;
      const old_leagues = [...leagues]; // [] becuase of initial state value, that is not updated
      const obj_index = old_leagues.findIndex(x => x.match_id == matchId);
      if(obj_index > -1) {
        old_leagues[obj_index] = { ...old_leagues[obj_index], pivotType, rateOver: rateOver, rateUnder:rateUnder, rateEqual:rateEqual};
        setLeagues(old_leagues);
      }
    }
  } 

  useEffect(() => {

    singleCall();

    var socket = io.connect('http://localhost:3001', {transports: ['websocket']});

    socket.on('connect', () => {
        console.log('socket connected:', socket.connected);
    });
    socket.on('odds_insert_one_two', function (record) {
      updateData(record);
    });

    socket.on('odds_update_one_two', function (record) {
      updateData(record);
    });

    socket.emit('get_odds_one_two');

    socket.on('disconnect', function () {
      console.log('socket disconnected, reconnecting...');
      socket.emit('get_odds_one_two');
    });

    return () => {
        console.log('websocket unmounting!!!!!');
        socket.off();
        socket.disconnect();
    };
  }, []);

推荐答案

useEffect 钩子是用一个空的依赖数组创建的,因此它只在初始化阶段被调用一次.因此,如果 league 状态被更新,它的值将永远不会在 updateData() 函数中可见.

The useEffect hook is created with an empty dependency array so that it only gets called once, at the initialization stage. Therefore, if league state is updated, its value will never be visible in the updateData() func.

您可以做的是将 league 值分配给 ref,并创建一个新的 hook,每次都会更新.

What you can do is assign the league value to a ref, and create a new hook, which will be updated each time.

const leaguesRef = React.useRef(leagues);

React.useEffect(() => {
  leaguesRef.current = leagues;
});

leagues 更新为 leaguesRef.current.

  const updateData = (record) => {
    for(const data of record) {
      var {matchId, pivotType, rateOver, rateUnder, rateEqual} = data;
      const old_leagues = [...leaguesRef.current]; // [] becuase of initial state value, that is not updated
      const obj_index = old_leagues.findIndex(x => x.match_id == matchId);
      if(obj_index > -1) {
        old_leagues[obj_index] = { ...old_leagues[obj_index], pivotType, rateOver: 
  rateOver, rateUnder:rateUnder, rateEqual:rateEqual};
        setLeagues(old_leagues);
      }
    }
  } 

这篇关于反应状态未使用 socket.io 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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