​redux-actions​​​有两大法宝​​createAction​​​和​​handleActions​​.

createAction

原来创建​​action​​:


const startAction = () => ({ type: START });

使用​​redux-actions​​​创建​​action​​:


import { createAction } from 'redux-actions';
const startAction = createAction(START);

handleActions

原来​​reducer​​​操作​​state​​​写法要使用​​switch​​​或​​if else​​来匹配:


function timer(state = defaultState, action) {
switch (action.type) {
case START:
return { ...state, runStatus: true };
case STOP:
return { ...state, runStatus: false };
case RESET:
return { ...state, seconds: 0 };
case RUN_TIMER:
return { ...state, seconds: state.seconds + 1 };
default:
return state;
}
}

使用​​redux-actions``reducer​​​操作​​state​​:


const timer = handleActions({
START: (state, action) => ({ ...state, runStatus: true }),
STOP: (state, action) => ({ ...state, runStatus: false }),
RESET: (state, action) => ({ ...state, seconds: 0 }),
RUN_TIMER: (state, action) => ({ ...state, seconds: state.seconds + 1 }),
}, defaultState);


作者:hello老文

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。