這篇 redux在react-native上使用(二)--加入saga 是使用redux-saga
, 可以跟這篇做個(gè)對(duì)比看下redux-thunk
和redux-saga
使用上的區(qū)別.
直接在這項(xiàng)目上修改, 只是把redux-thunk
替換了redux-saga
, 還是達(dá)到一樣的項(xiàng)目.
首先在package.json
里添加redux-thunk
庫(kù), 并在目錄下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
處理業(yè)務(wù)邏輯放在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
運(yùn)行.