根据activeStorage上设置的条件,尝试在打字稿博览会上返回不同的功能(带有视图)。
如果您在代码中查找,则在调用showIntro
时,我想显示从getScreen
返回的值,但是,当我控制台日志时,它将返回一个Promise对象
当我在await AsyncStorage.getItem('showIntro');
中管理getScreen
日志时,它给了我价值。
不确定是错误还是代码有问题?
import AsyncStorage from '@react-native-community/async-storage'
const data = [{...}, {...}, {...}]
const getScreen = async () => {
return await AsyncStorage.getItem('showIntro');
}
function App() {
const [showIntro, updateShowIntro] = React.useState(getScreen());
const onDone = () => {
AsyncStorage.setItem('showIntro', false).then(()=>{});
updateShowIntro(false);
}
return (
{ (showIntro) ? (
<AppIntroSlider
renderItem={renderItem}
data={data}
onDone={onDone}/>
) : (
<ShowApp />
)
}
);
}
答案 0 :(得分:3)
由于您正在使用getScreen
,因此您的Promise
返回async/await
。您需要做的是在组件首次加载到getScreen
挂钩中时调用React.useEffect
,然后在解析为您期望的任何值后更新showIntro
状态
使用async/await
函数“等待” AsyncStorage.getItem("showIntro")
使其具有一定的值才能返回,这实际上没有任何作用-您仍在处理Promise
,一旦“内部“ Promise
完成。
来自MDN:
return
值是一个Promise
,它将使用异步函数返回的值来解析,或者被异步函数抛出或未捕获的异常拒绝。
import AsyncStorage from '@react-native-community/async-storage'
const data = [{...}, {...}, {...}]
// no need for `async/await` here, using `async/await`
// turns your `getScreen` function into a `Promise`,
// you get the same exact result, so you might as well
// call your `AsyncStorage.getItem("showIntro")` function
// directly in the `React.useEffect` hook rather than
// through this `getScreen` function
const getScreen = () => {
return AsyncStorage.getItem("showIntro");
}
function App() {
const [showIntro, updateShowIntro] = React.useState(null);
React.useEffect(() => {
getScreen()
.then(result => {
updateShowIntro(result);
});
.catch(/* handle errors appropriately */);
// alternatively, just call `AsyncStorage.getItem("showIntro")` here
// AsyncStorage.getItem("showIntro")
// .then(result => { updateShowIntro(result); })
// .catch(/* handle errors appropriately */);
}, []);
const onDone = () => {
// should `updateShowIntro` be inside `then`?
AsyncStorage.setItem('showIntro', false)
.then(() => {
updateShowIntro(false);
})
.catch(/* handle errors appropriately */);
}
return showIntro ? (
<AppIntroSlider
renderItem={renderItem}
data={data}
onDone={onDone}
/>
) : (
<ShowApp />
);
}
参考: