04 July 2018

ReactJS + Redux: Sử dụng Middleware - Redux Middleware


Redux Middleware
ReatcJS 2018
import { applyMiddleware, createStore } from "redux";

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;
        case "ERROR":
            throw new Error("Error notification!");
            break;
    }
    return state;
}
const logger = (store) => (next) => (action) => {
  console.log("middleware logger");
  next(action);
}
const error = (store) => (next) => (action) => {
  try{
    next(action);
  } catch(e){
    console.log("middleware error",e);
  }
}

const middleware = applyMiddleware(logger, error);

const store = createStore(userReducer,1,middleware);

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: "ERROR", payload: 45});

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