如何在SSDP M-SEARCH设备发现中使用setState解决仅返回单台设备问题
问题原因
你的问题是React的闭包陷阱和引用类型判断逻辑错误共同导致的:
- 你在空依赖的
useEffect中调用getAllDevices,此时client.on的回调函数捕获的deviceList永远是初始化的空数组[],每次调用setDeviceList都是基于空数组拼接新url,前3次的更新都会被最后一次覆盖,最终只会保留最后捕获到的1台设备。 new URL()生成的是引用类型对象,即使两个URL的地址完全一致,也是不同的引用,用deviceList.includes(url)判断永远返回false,无法正确去重。
修复方案
修改状态更新逻辑为函数式更新,同时调整去重逻辑:
1. 调整设备添加逻辑
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) { // 采用函数式更新获取最新的deviceList setDeviceList(prevList => { // 用url的href字符串判断是否重复 const isExist = prevList.some(item => item.href === url.href); if (!isExist) { return [...prevList, url]; } return prevList; }) } }); };
2. 补充useEffect清理逻辑(防止内存泄漏)
useEffect(() => { getAllDevices(); return () => { // 可补充对应SSDP客户端的监听移除、实例销毁逻辑 // 示例:client.removeAllListeners('response') } }, []);
内容的提问来源于stack exchange,提问作者Ahmet Berk İnçoğlu
相关产品推荐
相关产品推荐

