【问题标题】:How To Display Wifi List Promise Values React Native如何显示 Wifi 列表 Promise 值 React Native
【发布时间】:2021-02-19 14:18:57
【问题描述】:

我正在使用 react-native-wifi-reborn 包来获取附近所有 wifi 点的列表。我如何从承诺中取出列表?我查看了一个解决方案,它使用了一个类,但是我的应用调用该函数来获取列表的地方,它不在一个中。

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}

【问题讨论】:

    标签: javascript react-native react-native-android


    【解决方案1】:

    这是一个 React 函数式组件的案例,与使用类相比,这是一种更简单的定义 React 组件的方法。在docs 中查看更多信息。

    在您的情况下,您的组件没有被更新并使用新的 wifiList 数据重新渲染,因为在您当前的代码中,您根本没有更新组件状态:

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

    在这种情况下,您将返回 data 结果作为一个承诺,但您没有使用它来更新组件状态,并且您也没有使用 await 来检索承诺结果。所以你实际上是在为wifiList分配一个Promise引用,而不是data结果的promise。

    要正确更新功能组件的状态,您可以使用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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2020-01-18
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多