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 middlewareconst 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);
}
}
以上是 react-redux(2) 的全部内容, 来源链接: utcz.com/z/383791.html