【问题标题】:asyncstorage + redux thunk + redux persist, callback on dispatchasyncstorage + redux thunk + redux 持久化,调度回调
【发布时间】:2017-09-16 12:34:51
【问题描述】:

我在我的 React Native 应用程序中使用 redux-thunk 以及 AsyncStorageredux-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 但我不认为它是一个可靠的选择。

【问题讨论】:

    标签: reactjs react-native redux-thunk


    【解决方案1】:

    您需要了解通量背后的基本原理。

    Action=> Dispatch=> 存储更新=> 通知订阅的模块

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 2018-03-19
      • 2021-04-05
      • 2017-09-15
      • 2019-04-06
      • 2018-05-21
      相关资源
      最近更新 更多