React系列: redux - bindActionCreators的使用方法

react-redux的connect方法

接受4个参数:

  1. mapStateToProps(state, [ownProps]) 接受完整的redux状态树作为参数,返回对象的所有key都会成为组件的props
  2. mapDispatchToProps(dispatch, [ownProps]) 接受redux的dispatch方法作为参数,返回当前组件相关部分的action creator并可以在这里将action creator与props绑定,减少冗余
  3. mergeProps(stateProps, dispatchProps, ownProps) 如果指定这个函数,你将分别获得 mapStateToProps、 mapDispatchToProps 返回值以及当前组件的props 作为参数,最终返回你期望的、完整的 props
  4. [options] : pure:true, 将为组件添加shouldComponentUpdate()声明周期函数;
    withRef:false, 若为true,为组件加一个ref值,后续可以使用 getWrappedInstance() 方法来获取该 ref

mapDispatchToProps可以是函数或者对象

可以把actioncreator绑定到props上,直接使用。绑定方法如下:

1.使用bindActionCreators

主要用于当想要把某些方法传递给子组件,并且不想传递dispatch等的时候用。

//./../../../redux/actions/customer.js
export const updateCustomerInfo = (payload = {}) => {
		return {
			type: 'ADD_CUSTOMER_INFO'
		}
}

export const toggleCustomerDrawer = (flag)=> {
	return {
		type: 'TOGGLE_CUSTOMER_DRAWER',
		payload: flag
	}
}
//
import {bindActionCreators} from 'redux';
import * as Actions from './../../../redux/actions/customer';

@connect(state => ({
	drawerInfo: state.customerDrawerInfo,
	curCustomer: state.cusomerInfo
}), dispatch=> ({
	...bindActionCreators(Actions, dispatch)
}))

通过以上方法绑定后,就可以直接调用this.props.updateCustomerInfo()来分发action

2.不用bindActionCreators,使用dispatch,两者效果一样
@connect(state => ({
	drawerInfo: state.customerDrawerInfo,
	curCustomer: state.cusomerInfo
}), dispatch=> ({
	updateCustomerInfo: (record) => {dispatch(Actions.updateCustomerInfo(record))}
}))


也可以上面两个都不用,用dispatch来分发action。

react-redux里的connect方法,可以把dispatch方法绑定到组件的props上, this.props(Actions.updateCustomerInfo(record))

发布了66 篇原创文章 · 获赞 13 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/haoyanyu_/article/details/100926765
今日推荐