如何在redux-persist中正确使用getStoredState

时间:2017-06-15 17:47:54

标签: reactjs react-native redux react-redux

我不确定我是否正确使用了redux-persist库中的getStoredState。我想使用已保留为默认redux商店的商店。

配置/ store.js

async function getState() {
  const storedState = await getStoredState({ storage: AsyncStorage });

  const store = createStore(reducers, storedState, compose(
    applyMiddleware(logger),
    autoRehydrate()
  ));
  persistStore(store, {storage: AsyncStorage);
}

export default getState();

App.js

import store from 'config/store';
import { Provider } from 'react-redux';

export default () => (
  <Provider store={store}>
    //
  </Provider>
)

这会产生以下警告:

Warning: Failed child context type: The child context `store.subscribe` is marked as required in `Provider`, but its value is `undefined`.

Warning: Failed prop type: The prop `store.subscribe` is marked as required in `Provider`, but its value is `undefined`

任何想法导致这些警告的原因是什么?我有一种感觉,我在store.js

做错了

1 个答案:

答案 0 :(得分:1)

问题在于,当您尝试实例化Provider时,您的store变量仍处于未决状态:getStoreState方法返回Promise,因此您必须等到它完成才能使用该存储。

此示例显示了一个示例实现:

import {getStoredState, createPersistor} from 'redux-persist'

class App extends Component {

  constructor(props) {
    super(props)
    this.store = null
    this.persistor = null
  }

  componentWillMount(){
    const persistConfig = {storage: AsyncStorage}
    getStoredState(persistConfig, (err, restoredState) => {
      this.store = createStore(
        reducers,
        restoredState,
        compose(
          applyMiddleware(logger,)
        )
      )
      this.persistor = createPersistor(this.store, persistConfig)
      // Now that we have the store setted, reload the component
      this.forceUpdate()
    })
   }

  render() {
    if (!this.store) {
      // Loading screen
      return <Text>Loading</Text>
    } else {
      return (
          <Provider store={this.store}>
            <Router />
          </Provider>
      )
    }

  }
}

欢迎任何改进提示。