React Native:从 AsyncStorage 加载值



如何在应用程序的第一页加载时将数据从 AsyncStorage 加载到 redux 存储?

我试图在componentWillMount中调用检查函数。

componentWillMount(){
debugger;
this.check();
}

在检查中,我试图从AsyncStorage中获取值并将其存储到 Redux 存储对象。

async check(){
await AsyncStorage.getItem('location').then((location) => {
this.props.location[0].city = location;
}
});
this.props.selectLocation(this.props.location);
}

由于它是一个异步函数,我无法获取值并将其存储在 reduxselectLocation操作的视图。

如何在组件安装之前正确获取数据并存储数据?

更新:

在我的 index.android 中.js我像这样更改了我的商店,

import { persistStore, autoRehydrate } from 'redux-persist'
import combineReducers from './src/Redux/reducers/combineReducers';
// const store = createStore(combineReducers);
const store = compose(autoRehydrate())(createStore)(combineReducers)
persistStore(store, {storage: AsyncStorage}, () => {
console.log('restored');
console.log(store);
})

export default class ReactNavigation extends Component {
render() {
return (
<Provider store = {store}>
<App />
</Provider>
);
}
}

组件应通过事件侦听器侦听存储的更改,并应在数据加载到存储时显示数据。

暂时,当数据不存在时,您应该显示类似微调器的内容,让用户知道它正在加载。

理想情况下,您不希望让 componentWillMount 等待数据加载。

最新更新