04 July 2018

ReactJS + Redux: Sử dụng nhiều Reducer - Multiple reducers with redux console

Multiple reducers
ReatcJS 2018
import { combineReducers, createStore } from "redux";

//Reducer lắng nghe các action gọi đến từ dispatch
const userReducer = (state={}, action) => {
    switch (action.type) {
        case "CHANGE_NAME":
            //state.name = action.payload;
            state = {...state, name: action.payload};
            break;
        case "CHANGE_AGE":
            //state.age = action.payload;
            state = {...state, age: action.payload};
            break;
    }
    return state;
}
const contactReducer = (state=[], action) => {
  switch (action.type) {
      case "CHANGE_EMAIL":
          //state.email = action.payload;
          state = {...state, email: action.payload};
          break;
      case "CLEAR":
          //state.age = action.payload;
          state = {...state, email: action.payload};
          break;
  }
  return state;
}
//Nhiều reducers
const reducers = combineReducers({
  user: userReducer,
  contact: contactReducer,
})
//Tạo mới store nội dung là function reducer
const store = createStore(reducers);
//Đăng ký store
store.subscribe(() => {
 console.log("store changed", store.getState())
})
//dispatch action
store.dispatch({type: "CHANGE_NAME", payload: "Antonio"});
store.dispatch({type: "CHANGE_AGE", payload: 45});
store.dispatch({type: "CHANGE_EMAIL", payload: "Antonio@example.com"});
store.dispatch({type: "CLEAR", payload: null});

ReactDOM.render(
    <App />,
   document.getElementById('root'));
npm start
Result

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang