我正在使用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次,但我只能得到一台设备。你能支持一下吗。
谢谢。
发布于 2021-10-21 09:11:15
我认为这更多的是一个竞争条件,而不是一个库问题。试着在setDeviceList上使用函数更新。
setDeviceList(deviceList => {
return [...deviceList, url]
}https://stackoverflow.com/questions/69653515
复制相似问题