redux在react-native上使用(三)--加入redux-thunk

这篇 redux在react-native上使用(二)--加入saga 是使用redux-saga,可以跟这篇做个对比看下redux-thunkredux-saga使用上的区别.

直接在这项目上修改,只是把redux-thunk替换了redux-saga,还是达到一样的项目.

首先在package.json添加redux-thunk库,并在目录下npm install:

"dependencies": {
    ...
    "redux-thunk": "^2.2.0"
},

sagas.js文件删除,修改store.js文件:

import { createStore,applyMiddleware,compose } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const configureStore = preloadedState => {
    return createStore (
        rootReducer,preloadedState,compose (
            applyMiddleware(thunk,createLogger())
        )
    );
}

const store = configureStore();
export default store;

redux-thunk处理业务逻辑放在action里,所以还要修改actions.js:

import { START,STOP,RESET,RUN_TIMER } from './actionsTypes';

const startAction = () => ({ type: START });
const stopAction = () => ({ type: STOP });
const resetAction = () => ({ type: RESET });
const runTimeAction = () => ({ type: RUN_TIMER });

var t = -1;

export const start = ()=> {
  return dispatch => {
    dispatch(startAction());
    if(t != -1) return;
    t = setInterval(() => {
      dispatch(runTimeAction());
    },1000);
  };
}

export const stop = ()=> {
  return dispatch => {
    dispatch(stopAction());
    if (t != -1) {
      clearInterval(t);
      t = -1;
    }
  }
}

export const reset = ()=> {
  return dispatch => {
    dispatch(resetAction());
    dispatch(stop());
  }
}

OK,大功告成,commond+R运行.

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...