React依赖注入说明(mapStateToProps/mapDispatchToProps)

本博客主要来讲一下React依赖注入说明,其中涉及到mapStateToProps()和mapDispatchToProps()两个函数。


在react-redux开发中每个模块有自己的state用来统一管理视图数据

(1)将需要的state的节点注入到与此视图数据相关的组件上

function mapStateToProps(state, ownProps) {
    return {
        loading:state.getIn(['APP', 'loading']),
        data:state.getIn(['APP', 'data'])
    }
    // loading、data都是来自对应的reduce
}

(2)将需要绑定的响应事件注入到组件上

function mapDispatchToProps(dispatch){
    return {
        ...bindActionCreators(action, dispatch)
    }
}
// mapDispatchToProps()函数的bindActionCreators、action需要引入
    // import * as action from '../action';
    // import { bindActionCreators } from 'redux';



------------------------------------
------------------------------------
// 多个action 引入
import * as action from '../action';
import * as action2 from '../../index/action';
function mapDispatchToProps(dispatch){
    return {
        ...bindActionCreators(action, dispatch),
        ...bindActionCreators(action2, dispatch)
    }
}

------------------------------------
------------------------------------
// 引入一个action里面的多个方法
import { function1, function2, function3 } from '../webs/action'
function mapDispatchToProps(dispatch) {
  return {
    ...bindActionCreators({ afunction1, function2, function3 }, dispatch)
  }
}

(3)统筹mapStateToProps和mapDispatchToProps

export default connect(mapStateToProps, mapDispatchToProps)(DemoClass)
// OtherMsg 是类名
// class DemoClass extends React.Component { // 具体的内容}

(4)综合

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as action from '../action';
import * as action2 from '../../../inde/action';
import { function1, function2, function3 } from '../webs/action'

class DemoClass extends React.Component {
    render() { return ( 
) } } function mapDispatchToProps(dispatch){ return { ...bindActionCreators(action, dispatch), ...bindActionCreators(action2, dispatch), ...bindActionCreators({ function1, function2, function3 }, dispatch) } } function mapStateToProps(state, ownProps) { return { loading:state.getIn(['APP', 'loading']), data:state.getIn(['APP', 'data']), } } export default connect(mapStateToProps, mapDispatchToProps)(DemoClass)

最后,说一下常规react-redux开发的基本结构

开发环境调用后台路径配置:可以使用代理,例如`proxy.config.js`

各个模块目录下:
> api      定义与后台交互的接口方法  api.js
> action   定义页面操作触发的动作    action.js
> reducer  定义触发动作后的影响      reducer.js

你可能感兴趣的:(React)