React Native:从AsyncStorage加载值

时间:2017-07-29 08:08:51

标签: reactjs react-native redux react-redux 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);
}

由于它是异步函数,我无法获取值并将其存储为redux的selectLocation视图。

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

更新

在我的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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您的组件应该通过事件侦听器监听存储以进行更改,并且应该在将数据加载到存储中时显示数据。

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

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