Redux 中间件是什么?接受几个参数?柯里化函数两端的参数具体是什么 ?
Redux 中间件是一种强大的工具,可以用来处理异步操作和扩展 Redux 的功能。它位于 action 被派发和到达 reducer 之间的过程中,提供了一个扩展点来影响或者修改这个过程。
Redux 中间件是一个柯里化函数,它接收三个参数:
- storeAPI:这个对象包含了两个方法:
dispatch
和getState
。dispatch
可以让你派发 actions,getState
可以让你访问当前的 state。 -
next:这是一个指向被当前中间件包装过的
dispatch
方法的引用。你可以调用next(action)
来传递 action 给下一个中间件(如果有的话),或者直接到达 reducer 如果没有更多的中间件。 -
action:这是被派发的 action。中间件可以读取这个 action,修改它,停止它,或者根据它产生新的 actions 来派发。
以下是一个简单的中间件例子,这个中间件会在每个 action 被派发时打印出当前的 state 和这个 action:
const loggerMiddleware = storeAPI => next => action => {
console.log('dispatching', action)
console.log('state before dispatch', storeAPI.getState())
// Call the next dispatch method in the middleware chain.
let result = next(action)
console.log('state after dispatch', storeAPI.getState())
// This will likely be the action itself, unless
// a middleware further in chain changed it.
return result
}
在这个例子中,storeAPI
是中间件的第一个参数,next
是第二个参数,action
是第三个参数。这个中间件首先打印出被派发的 action 和派发前的 state,然后调用 next(action)
来传递 action 给下一个中间件或者 reducer,最后打印出派发后的 state。