猿问

applyMiddleware的参数为什么加展开符?

export default function applyMiddleware(...middlewares) {

  return (createStore) => (reducer, preloadedState, enhancer) => {

    const store = createStore(reducer, preloadedState, enhancer)

    let dispatch = store.dispatch

    let chain = []


    const middlewareAPI = {

      getState: store.getState,

      dispatch: (action) => dispatch(action)

    }

    chain = middlewares.map(middleware => middleware(middlewareAPI))

    dispatch = compose(...chain)(store.dispatch)


    return {

      ...store,

      dispatch

    }

  }

}

这里参数为什么要用展开符? 使用的时候传入的是数组,如:
const middlewares = [ thunk, logger ]
applyMiddleware(...middlewares)
那这样函数中 middlewares.map 的 middlewares岂不是 [[thunk, logger]]了么。

PS: 奥。。明白了,同时支持applyMiddleware(thunk, logger)和applyMiddleware(...[thunk, logger])两种方式调用。 
大家忽略吧


回首忆惘然
浏览 627回答 1
1回答

倚天杖

这里用...middlewares,在ES6中叫做[不定参数][1],和arguments的效果类似,把传入的所有参数,作为一个array赋值给middlewares例子:function test(...args) {    console.log(args); // [1,2,3]} test(1,2,3)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答