如何使用setState与ssdp m-search发现?



我正在使用SSDP搜索消息来发现连接相同网络的设备,但当我试图在客户端内部调用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次,但我只能得到一个设备。你能不能支持一下。

谢谢。

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

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