react.js - redux 官方案例 examples/todos 有一处看不懂.

查看:137
本文介绍了react.js - redux 官方案例 examples/todos 有一处看不懂.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

学习 redux 的官方案例 : https://github.com/reactjs/re...

发现有一个地方看不懂 :

点击当前 todo 切换完成状态, 对应触发的 actionTOGGLE_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆