Redux异步Action

参考:https://github.com/react-guide/redux-tutorial-cn

import { applyMiddleware, combineReducers, createStore } from "redux";
function thunkMiddleware({ dispatch, getState }) {
  console.log("Enter thunkMiddleware");
  return function(next) {
    console.log('Function "next" provided:', next);
    return function(action) {
      console.log("Handling action:", action);
      return typeof action === "function"
        ? action(dispatch, getState)
        : next(action);
    };
  };
}
const finalCreateStore = applyMiddleware(thunkMiddleware)(createStore);
let reducer = combineReducers({
  speker: function(state = {}, action) {
    console.log("speaker is called with state", state, "and anction", action);
    switch (action.type) {
      case "SAY":
        return Object.assign({}, state, { message: action.message });
      default:
        return state;
    }
  }
});
console.log("*********************分隔线**********************");
const store = finalCreateStore(reducer);
console.log(store.getState());
function asyncActionCreator(message = "Hi") {
  return function(dispatch, getState) {
    setTimeout(function() {
      console.log(new Date().toString());
      dispatch({ type: "SAY", message: message });
      console.log("In asyncActionCreator",getState());
    }, 2000);
  };
}
console.log(new Date().toString());
store.dispatch(asyncActionCreator("这里是异步action"));

 

你可能感兴趣的:(Web前端,Redux,React,JavaScript,异步,Action)