redux 初步學習
創建reduce
const counterReducer = function(state: any = {count: 1}, action: any) {
switch(action.type){
case 'COUNT_ADD':
return {...state, count: state.count + 1};
default:
return state;
}
}
state初始設置爲{count:1}
多個reducer可以合併成一個
const rootReducers = combineReducers({
counter: counterReducer,
post: postReducer
});
創建store
const store = createStore(
rootReducers
);
使用
store.dispatch({
type: 'COUNT_ADD',
payload: {}
});
有異步代碼時需要使用redux-thunk
import thunk from 'redux-thunk';
const store = createStore(
rootReducers,
compose(
applyMiddleware(...[thunk]),
(window as any).__REDUX_DEVTOOLS_EXTENSION__ && (window as any).__REDUX_DEVTOOLS_EXTENSION__(), // redux-devtools 插件的使用
)
);