[英]Unable to return IP address using react-native-device-info's getIPAddress()
I need to return the IP address for the device running my React Native app (an Android smart tv app).我需要为运行我的 React Native 应用程序(Android 智能电视应用程序)的设备返回 IP 地址。 I am making use of react-native-device-info which has allowed me to get the model, manufacturer and operating system.
我正在使用 react-native-device-info,它允许我获得 model、制造商和操作系统。 However I am unable to get the ip address.
但是我无法获得 ip 地址。
This is my code这是我的代码
deviceInfo = DeviceInfo.getIPAddress().then(ip => {
return ip;
});
However on the front end it appears as [object Object].但是在前端它显示为 [object Object]。 I can see in the console it is returning an object like this:
我可以在控制台中看到它正在返回一个 object,如下所示:
wifi:
_40: 0
_55: null
_65: 0
_72: null
I would have hoped to just return a string of the correct IP address.我本来希望只返回一个正确的 IP 地址的字符串。
I have also added the right permissions in my AndroidManifest.xml.我还在我的 AndroidManifest.xml 中添加了正确的权限。
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Also worth noting I am passing the information back by value: ${JSON.stringify(deviceInfo)}
同样值得注意的是,我正在按
value: ${JSON.stringify(deviceInfo)}
Any one experienced this issue before?以前有人遇到过这个问题吗?
I have used below library: https://www.npmjs.com/package/react-native-network-info我使用了以下库: https : //www.npmjs.com/package/react-native-network-info
And it is working fine, Below is the code:它工作正常,以下是代码:
// Get IPv4 IP (priority: WiFi first, cellular second)
NetworkInfo.getIPV4Address().then(ipv4Address => {
console.log(ipv4Address); //result e.g 192.168.1.100
});
You are basically assigning the promise from DeviceInfo.getIPAddress()
to the value deviceInfo
. 您基本上是将
DeviceInfo.getIPAddress()
的promise分配给值deviceInfo
。 You cannot return the value from your .then
as you are currently doing. 您无法像目前那样从
.then
返回值。
To overcome this you should do something like this, this will wait for the promise to resolve and allow you to get the ip address. 为了克服这个问题,您应该执行类似的操作,这将等待promise解决并允许您获取IP地址。 Remember you need to wrap an
await
in a try/catch
as it can throw. 请记住,您需要在
try/catch
包装一个await
,因为它可能会抛出。
try {
let ipAddress = await DeviceInfo.getIPAddress()
// now use the ipAddress
} catch (error) {
console.log(error)
}
Since its returning a promise try putting inside a async function and try to get the result.由于它返回 promise 尝试放入异步 function 并尝试获得结果。
Ex:前任:
const getIpAddress = async()=>{
const ip = await DeviceInfo.getIPAddress();
console.log(ip);
return ip;
}
Hope it helps.希望能帮助到你。 Thank you.
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.