react.js - redux 官方案例 examples/todos 有一处看不懂.
问题描述
学习 redux 的官方案例 : https://github.com/reactjs/re...
发现有一个地方看不懂 :
点击当前 todo 切换完成状态, 对应触发的 action
是 TOGGLE_TODO
, 但是我发现并没有调用 dispatch()
, 为什么整个应用的 state
就变化了?
containers/VisibleTodoList.js
:
const mapStateToProps = (state) => ({
todos: getVisibleTodos(state.todos, state.visibilityFilter)
})
const mapDispatchToProps = ({
onTodoClick: toggleTodo
})
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
在 mapDispatchToProps
里并没有调用 dispatch()
.
这里是怎么触发了 state 的变更?
文档里其实已经写了
[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): If an object is passed, each function inside it will be assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props
这里说了mapDispatchToProps
的参数如果是一个object
的话,里面的每个函数都会被当做一个action creator
,因此这个对象上的每个函数都会用dispatch
包一层,然后传给props
,因此你看到的props
上的onTodoClick
其实是已经有dispatch
了
正好我之前看过redux的源码,给你讲下
//这是redux处理mapDispatchToProps的
if (typeof mapDispatchToProps === 'function') {
mapDispatch = mapDispatchToProps
} else if (!mapDispatchToProps) {
mapDispatch = defaultMapDispatchToProps
} else { //因为你的mapDispatchToProps的入参是个object,进了这里的分支逻辑
mapDispatch = wrapActionCreators(mapDispatchToProps)
}
再看看wrapActionCreators
import { bindActionCreators } from 'redux'
//看,你的对象其实是被bindActionCreators给包裹了
export default function wrapActionCreators(actionCreators) {
return dispatch => bindActionCreators(actionCreators, dispatch)
}
至于bindActionCreators
是做什么的可以去看看文档了
这篇关于react.js - redux 官方案例 examples/todos 有一处看不懂.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!