Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redux源码解读拾遗,createStore的第三个参数 #11

Open
forthealllight opened this issue Jun 5, 2018 · 3 comments
Open

Redux源码解读拾遗,createStore的第三个参数 #11

forthealllight opened this issue Jun 5, 2018 · 3 comments

Comments

@forthealllight
Copy link
Owner

forthealllight commented Jun 5, 2018

简要介绍:再看redux文档的时候,发现了createStore是允许第三个参数的,看了一下源码明白了第三个参数的作用。

一、createStore的第三个参数的定义

(1) 官方定义:createStore(reducer, [initialState], enhancer),

第三个参数enhancer, 是一个组合 store creator 的高阶函数,返回一个

新的强化过的 store creator。这与 middleware 相似,它也允许你通过

复合函数改变 store 接口。

(2) 关于第三个参数的源码:

export default function createStore(reducer, preloadedState, enhancer) {
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState
    preloadedState = undefined
  }

  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }

    return enhancer(createStore)(reducer, preloadedState)
  }

去掉前面一些类型判断,我们来看这一句:

 return enhancer(createStore)(reducer, preloadedState)

这句的形式像什么,柯里化后传入的第一个参数为createStore,这很类

似于我们再定义中间件的时候,applyMiddleware这个函数,这个函数

返回了提升后的createStore。

二、applyMiddleware的两种写法

因此在applyMiddleware的时候,就会存在两种写法,这里我们以利用redux-thunk为例。

(1) 直接调用applyMiddleware生成新的createStore

import thunk from 'redux-thunk'
let createStoreWithMiddleware = applyMiddleware(thunk)(createStore)

(2) 在createStore中调用

import thunk from 'redux-thunk'
let createStoreWithMiddleware = createStore(reducer,preState,applyMiddleware(thunk))

@forthealllight forthealllight changed the title Redux源码解读拾遗-createStore的第三个参数 Redux源码解读拾遗,createStore的第三个参数 Jun 5, 2018
@clerkkent
Copy link

试试装饰器方式去写,比较容易理解

@forthealllight
Copy link
Owner Author

好的好的~

@clerkkent
Copy link

有没兴趣来百度🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants