reac之reducer初步使用

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 插件的使用
  )
);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章