好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

react-redux的connect示例详解

connect 简介:
connect 是 react-redux 两个api中其中之一,在使用 react-redux 时起到了为 redux 中常用的功能实现了和 react 连接的建立
函数入口,以及需要传入的参数:

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {}

mapStateToProps:
传入所有state,返回指定的state数据。

function mapStateToProps(state) {
      return { todos: state.todos }
    }

mapDispatchToProps:
传入dispatch,返回使用绑定的action方法。

function mapDispatchToProps(dispatch) {
  return bindActionCreators(Object.assign({}, todoActionCreators, counterActionCreators), dispatch)
}

mergeProps:
mergeProps如果不指定,则默认返回 Object.assign({}, ownProps, stateProps, dispatchProps),顾名思义,mergeProps是合并的意思,将state合并后传递给组件

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, ownProps, {
    todos: stateProps.todos[ownProps.userId],
    addTodo: (text) => dispatchProps.addTodo(ownProps.userId, text)
  })
}

**options:**通过配置项可以更加详细的定义connect的行为,通常只需要执行默认值。 connect函数解析思路“
connect函数是核心既然是函数,那就有返回值,connect()返回值是Connect组件,通俗点理解,使用connect可以把state和dispatch绑定到react组件,使得组件可以访问到redux的数据。
我们常用的写法如下:

export default connect(mapStateToProps)(TodoApp)

原文地址:https://blog.csdn.net/qq_38980678/article/details/128798799

查看更多关于react-redux的connect示例详解的详细内容...

  阅读:34次