如何显示 Wifi 列表承诺值 React Native

How To Display Wifi List Promise Values React Native

我正在使用 react-native-wifi-reborn 包来获取附近所有 wifi 点的列表。我如何从承诺中获得清单?我看过一个解决方案,它使用 class,但我的应用程序调用该函数来获取列表的地方不在其中。

const MainScreen = ({navigation}) => {

    requestFineLocationPermission();

    WifiManager.setEnabled(true);
    let wifiList = WifiManager.reScanAndLoadWifiList().then((data) => {return data});

    console.log(wifiList);

    return (

        <Layout style={styles.container}>
                
                ......

        </Layout>
    );
}

export default MainScreen;

记录 wifiList 时,输出为 {"_U": 0, "_V": 0, "_W": null, "_X": null}

这是一个 React 功能组件的案例,与使用 类 相比,这是一种定义 React 组件的更简单的方法。在 docs.

中查看更多信息

在您的情况下,您的组件未使用新的 wifiList 数据更新和重新呈现,因为在您当前的代码中,您根本没有更新组件状态:

    let wifiList = WifiManager.reScanAndLoadWifiList().then((data) => {
      return data
    });

在这种情况下,您将返回 data 结果作为承诺,但您没有使用它来更新组件状态,也没有使用 await 来检索承诺结果。因此,您实际上是将 Promise 引用分配给 wifiList,而不是 Promise data 结果。

要正确更新功能组件的状态,您可以使用 React hook useState()

结果类似于:

const MainScreen = ({navigation}) => {

    requestFineLocationPermission();

    const [wifiList, setWifiList] = useState(/* initialValue */); // you may provide an initial value (optional, defaults to undefined)

    WifiManager.setEnabled(true);
    WifiManager.reScanAndLoadWifiList().then((data) => { 
      // update the state here
      setWifiList(data);
    });

    // this will log the initialValue 'undefined' the first time, 
    // then after state is is updated, 
    // it will log the actual wifi list data, resolved by 'WifiManager.reScanAndLoadWifiList()'
    console.log(wifiList);

    return (

        <Layout style={styles.container}>
                
                ......

        </Layout>
    );
}

export default MainScreen;