【问题标题】:How to use setState with ssdp m-search discovery?如何将 setState 与 ssdp m-search 发现一起使用?
【发布时间】:2021-12-07 17:15:34
【问题描述】:

我正在使用 SSDP 搜索消息来发现连接相同网络的设备,但是当我尝试在 client.on 函数中调用 setState 挂钩时,我只得到一个设备信息。

我用这种方式初始化了我的状态值

const [deviceList, setDeviceList] = useState([]);

并为客户端创建一个函数,以便在找到时添加 deviceList

const getAllDevices = () => {

var Client = require('react-native-ssdp-remote').Client,
  client = new Client();

client.search('urn:dial-multiscreen-org:service:dial:1');

client.on('response', function (headers) {
  const url = new URL(headers.LOCATION);
  if (url != null) {
    if (!deviceList.includes(url)) {
      setDeviceList([...deviceList, url]);
    }
  }
});
};

并在 useEffect 中调用了这个函数

  useEffect(() => {
  getAllDevices();
  }, []);

有 4 台设备连接到同一个网络,它进入 setDeviceList 进程 4 次,但我只能获得一台设备。能否请您支持一下。

谢谢。

【问题讨论】:

  • 您的代码似乎没问题。看起来您面临的问题与名为“react-native-ssdp”的 RN 库有关,而与 useState 挂钩无关。您是否已经检查了库规范以获得获取所有客户端列表的正确方法?
  • 感谢您的回复。是的,我检查了库和示例用法 (github.com/netbeast/react-native-ssdp/blob/master/example/…) 它不会立即返回所有客户端,每次找到设备时都会进入 client.on。出于这个原因,我认为它可能与 useState 有关。

标签: react-native react-hooks ssdp


【解决方案1】:

我认为这更像是一种竞争条件,而不是库问题。 尝试在 setDeviceList 上使用功能更新。

setDeviceList(deviceList => {
   return [...deviceList, url]
}

【讨论】:

  • 当我以这种方式实现时,我能够正确获取设备列表。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 2019-09-27
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多