redux的bindActionCreators源码,中文翻译

30次阅读

共计 2118 个字符,预计需要花费 6 分钟才能阅读完成。

function bindActionCreator(actionCreator, dispatch) {
return (…args) => dispatch(actionCreator(…args))
}

/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* 将一个 value 值是 action 创建函数的对象变成一个具有相同 key 值的对象, 但是每个函数都被封装到
* `dispatch` 回调里面, 这样它们就有可能被直接触发. 这样只是比较方便, 你也可以调用
* `store.dispatch(MyActionCreators.doSomething())`
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* 为了方便, 你也可以传单个函数作为第一个参数, 然后返回一个函树
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* actionCreators 是一个 value 值是 action 创建函数的对象, 一个很方便获取到它的方法就是
* 使用 ES6 的 `import * as ` 语法. 也可以传单个函数
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* dispatch 就是 redux 里 store 的 dispatch
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*
* 返回的对象和初始的对选象很像, 但每一个 action 创建函数都给封装到 `dispatch` 回调里面
* 如果你传单个函数作为 `actionCreators`, 那返回值也是一个单个函数
*/
export default function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === ‘function’) {
return bindActionCreator(actionCreators, dispatch)
}

if (typeof actionCreators !== ‘object’ || actionCreators === null) {
throw new Error(
`bindActionCreators expected an object or a function, instead received ${actionCreators === null ? ‘null’ : typeof actionCreators}. ` +
`Did you write “import ActionCreators from” instead of “import * as ActionCreators from”?`
)
//bindActionCreators 的参数应该是对象或者函数, 而不是空或其他类型,
// 你是不是把 ”import * as ActionCreators from” 写成了 ”import ActionCreators from”?
}

const keys = Object.keys(actionCreators)
const boundActionCreators = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const actionCreator = actionCreators[key]
if (typeof actionCreator === ‘function’) {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
源码解析请参考 https://segmentfault.com/a/11…

正文完
 0