【发布时间】: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