简体   繁体   English

将 promise 的值存储到一个变量中,以便稍后与 state 一起使用。 (反应原生)

[英]Store the value of a promise into a variable to use later with state. (React-Native)

const storage = AsyncStorage.getItem('@location_data').then(data => data)
const App = () => {
    const [locationData, setLocationData] = useState(storage);

Storage currently holds a promise, how could I get storage to become the value of the promise?存储目前持有一个promise,如何让存储成为promise的值?

AsyncStorage Documentation 异步存储文档

Your code (as of writing), is setting storage as a promise, your state will now contain a promise.您的代码(在编写时)将存储设置为 promise,您的 state 现在将包含 promise。 The way you have the then(data => data) is doing nothing to your data except adding a (redundant) chain to the promise.您拥有then(data => data)的方式除了向 promise 添加(冗余)链外,对您的数据没有任何作用。

You either need to await the promise to finish inside an async function.您要么需要等待promise 在异步 function 内完成。

const data = await AsyncStorage.getItem('@location_data');
const [locationData, setLocationData] = useState(data);

Or, set the state of the promise within then() :或者,在then()中设置 promise 的 state :

AsyncStorage.getItem('@location_data').then(data => {
    setLocationData(data)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM