asyncstorage + redux thunk + redux persist,sendatch on dispatch

时间:2017-04-20 04:01:50

标签: reactjs react-native redux-thunk

我在我的反应原生应用中使用redux-thunk以及AsyncStorage& redux-persist。因此,在发送行动后,变更状态自然会有延迟。

import { compose, createStore, applyMiddleware } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import reducers from '../reducers';
import { AsyncStorage } from 'react-native';
import createLogger from 'redux-logger';

const logger = createLogger({
  predicate: () => process.env.NODE_ENV === 'development'
});

const middleWare = [ thunk, logger ];

const createStoreWithMiddleware = applyMiddleware(...middleWare)(createStore);

export function makeStore(onComplete :? () => void) {
  const store = autoRehydrate()(createStoreWithMiddleware)(reducers);
  persistStore(store, {
    storage: AsyncStorage
  }, onComplete);
  return store;
}

export default makeStore;

在我的情况下

console.log(this.props.counter); // 1
this.props.dispatch(incrementCounter());
console.log(this.props.counter); // still 1 ?

所以我需要做的是在调度函数上添加Promise之类的回调,如

this.props.dispatch(incrementCounter())
    .then(() => console.log(this.props.counter)); // 2

我该怎么做到这一点?我已经使用了setTimeout,但我认为它不是一个可靠的选择。

1 个答案:

答案 0 :(得分:1)

你需要了解背后的基本知识。

动作=>调度=>商店更新=>已通知订阅的模块

在您的情况下,没有超时可以工作,您必须订阅商店以获得有关商店更新的通知。

http://redux.js.org/docs/api/Store.html#subscribe