react-redux(2)

时间:2023-03-08 23:15:09
react-redux(2)

中间件

机制:

  • 建立一个store.dispatch的链条,每个middleware是链条中的一个环节,传入的action对象逐步处理,直到最后出来是Javascript Plain Object;
import { createStore, combineReducers, applyMiddleware } from 'redux';

// applyMiddleware takes createStore() and returns// a function with a compatible API.
let createStoreWithMiddleware = applyMiddleware(
logger,
crashReporter
)(createStore); // Use it like you would use createStore()let todoApp = combineReducers(reducers);
let store = createStoreWithMiddleware(todoApp);

middleware

`// Logs all actions and states after they are dispatched.
const logger = store => next => action => {
console.log('dispatching', action);
let result = next(action);
console.log('next state', store.getState());
return result;
};`
  • 每一个 Middleware 可以得到:
    • store: 通过store.getState获得最近的状态;以及通过原本的dispatch对象直接发布action对象;
    • next方法: 前一个Middleware返回的dispatch方法;

Thunk

  • 实现传名调用(只在执行时求值)的临时函数;
//Thunk middleware
const thunk = store => next => action => {
typeof action === 'function' ?
action(store.dispatch, store.getState) :
next(action);
}
  • 加入这个中间件后,再action中定义异步的方法
export function incrementIfOdd () {
return (dispatch, getState) => {
const {counter} = getState();
if(counter % 2 === 0) return;
dispatch(increment());
}
} export function incrementAsync(delay = 1000) {
return dispatch => {
setTimeout(()=> {
dispatch(increment());
}, delay);
}
}