【问题标题】:Recact state is not being updated when using socket.io and react hooks [duplicate]使用 socket.io 和反应钩子时反应状态没有被更新 [重复]
【发布时间】:2021-03-18 15:49:06
【问题描述】:

我有一个像下面这样的组件。

import React,{useEffect,useState} from "react";
import {Marker} from "react-map-gl";
import io from "socket.io-client";
import { BASE_URL } from "../../../config/urls";
const socket = io(BASE_URL, {
    query: {
      token:
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXV",
    },
  });

export default function Route(){
    const [markerPos, setMarkerPos] = useState({
        longitude:8.5455940,latitude:47.3977421
    })
    const update=(data)=>{
        const obj = {
            longitude:data['gps.lon'],
            latitude:data['gps.lat']
        }
        setMarkerPos(prevProps =>{
            return {...prevProps,longitude:obj.longitude,latitude:obj.latitude}
        });
        console.log(markerPos.longitude,data['gps.lon'])
    }
    useEffect(()=>{
        socket.on("mission_data",(socketData)=>{
            update(socketData)
        })
    },[])

    return null;
}

访问 StackOverflow 上的一些问题时,我想到了这个解决方案。

问题:

Why is my state not being updated using React Hooks?
React State is not updated with socket.io
React Hooks: state not updating when called inside Socket.io handler
React State is not updated with socket.io

socket.on 只被调用一次。 虽然,socketData 总是会更新。每次新数据来自socket.io。

您可以在上图中看到,红色的右侧数据来自套接字并且正在更新。但是,左侧的绿色数据是反应状态变量没有更新。

编辑

此问题与useState set method not reflecting change immediately 不重复。

我知道反应异步更新状态。因此,状态更新不会立即反映。

在我的情况下,状态甚至没有更新,我等了一个小时。

【问题讨论】:

  • 可能不会在公开发布的代码中包含您的 API 令牌...
  • @Matt 我已经删除了大约 10 到 12 个字符的 API,所以,这不会造成任何问题。
  • "在我的情况下,状态甚至没有更新,我等了一个小时。" ——这没有任何意义。当然它已经更新了,只是在它更新时你不会在任何地方打印它。
  • @GuyIncognito not printing it anywhere 我在控制台上打印,见console.log(markerPos.longitude,data['gps.lon'])
  • 是的。您正在打印它在它更新之前。 在它更新之后,您不会打印它。

标签: reactjs socket.io use-effect use-state


【解决方案1】:

markerPos 的状态是异步更新的。尝试渲染 MarkerPos,您应该会看到它发生了变化。如果你想在函数发生变化时调用它,请使用另一个 useEffect 钩子

import React,{useEffect,useState} from "react";
import {Marker} from "react-map-gl";
import io from "socket.io-client";
import { BASE_URL } from "../../../config/urls";
const socket = io(BASE_URL, {
    query: {
      token:
        "xxxxxxx",
    },
  });

export default function Route(){
    const [markerPos, setMarkerPos] = useState({
        longitude:8.5455940,latitude:47.3977421
    })
    const update=(data)=>{
        const obj = {
            longitude:data['gps.lon'],
            latitude:data['gps.lat']
        }
        setMarkerPos(prevProps =>{
            return {...prevProps,longitude:obj.longitude,latitude:obj.latitude}
        });
        console.log(markerPos.longitude,data['gps.lon'])
    }
    useEffect(()=>{
        socket.on("mission_data",(socketData)=>{
            update(socketData)
        })
    },[])

    useEffect(()=>{
       console.log(markerPos)
    },[markerPos])
    return null;
}

【讨论】:

  • 在这里,我们列出了更改markerPos,我不认为这会起作用。但是,我正在尝试这个。
  • 在你的组件中,Route组件没有重新渲染,因为props没有chaning,所以没有必要更新markerPos状态,因为它没有被使用
猜你喜欢
  • 2020-12-01
  • 2020-08-31
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多