React Native AsyncStorage 在渲染后获取数据
我在 ComponentWillMount
中使用 AsyncStorage
来获取本地存储的 accessToken
,但它在 render()
函数已运行.如何让 render()
等到承诺完成?谢谢.
I am using AsyncStorage
in ComponentWillMount
to get locally stored accessToken
, but it is returning the promise after render()
function has run. How can I make render()
wait until promise is completed? Thank you.
据我所知,你不能让组件等待渲染.我在我正在开发的应用程序中所做的是添加一个加载屏幕,直到 AsyncStorage 的承诺得到解决.请参阅以下示例:
You can't make a component wait to render, as far as I know. What I've done in the app I'm working on is to add a loading screen until that promise from AsyncStorage resolves. See the examples below:
//
// With class component syntax
//
import React from 'react';
import {
AsyncStorage,
View,
Text
} from 'react-native';
class Screen extends React.Component {
state = {
isLoading: true
};
componentDidMount() {
AsyncStorage.getItem('accessToken').then((token) => {
this.setState({
isLoading: false
});
});
},
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
}
}
//
// With function component syntax and hooks (preferred)
//
import React, { useEffect } from 'react';
import {
AsyncStorage,
View,
Text
} from 'react-native';
const Screen () => {
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
AsyncStorage.getItem('accessToken').then((token) => {
setIsLoading(false);
});
}, [])
if (isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
}
在 state 中设置 isLoading
属性将导致重新渲染,然后您可以显示依赖于 accessToken 的内容.
Setting the isLoading
property in state will cause a re-render and then you can show the content that relies on the accessToken.
顺便说一句,我写了一个名为 react-native 的小库-simple-store 简化了 AsyncStorage 中的数据管理.希望你觉得它有用.
On a side note, I've written a little library called react-native-simple-store that simplifies managing data in AsyncStorage. Hope you find it useful.