将参数传递给redux调度函数

时间:2018-04-16 00:31:26

标签: javascript reactjs redux event-handling

我想构建一些按钮(来自react-bootstrap按钮),这些按钮知道鼠标光标何时进入并离开它们。连接它没问题,我得到的一切都很好。但是,如果我有几个这样的按钮,并且每个按钮都有一个名称传递给它,我如何将名称输入减速器?

在以下示例中,我希望将mapsDispatchToProps传递给reducer,看一看import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Button } from 'react-bootstrap'; const InteractiveButton = ({ bsStyle, bsName, bsText, dispButtonEnter, dispButtonLeave }) => ( <div> <Button onMouseEnter={dispButtonEnter} onMouseLeave={dispButtonLeave} bsStyle={bsStyle} bsSize="large" title={bsName} block > {bsText} </Button> </div> ); InteractiveButton.propTypes = { bsStyle: PropTypes.string.isRequired, bsName: PropTypes.string.isRequired, bsText: PropTypes.string.isRequired, dispButtonEnter: PropTypes.func.isRequired, dispButtonLeave: PropTypes.func.isRequired }; const dispButtonEnter = { type: 'BUTTON_MOUSE_ENTER' }; const dispButtonLeave = { type: 'BUTTON_MOUSE_LEAVE' }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { dispButtonEnter: e => dispatch({ ...dispButtonEnter, buttonName: bsName <<<<<<<<<<<<<<<<<<<<<<<< something like this, but functioning buttonEnterTarget: e.relatedTarget }), dispButtonLeave: e => dispatch({ ...dispButtonLeave, buttonName: bsName <<<<<<<<<<<<<<<<<<<<<<<< something like this, but functioning buttonLeaveTarget: e.relatedTarget }) }; } export default connect(mapStateToProps, mapDispatchToProps)(InteractiveButton);

{{1}}

1 个答案:

答案 0 :(得分:1)

您应该正确使用闭包这里不要直接调度,而是调用将接收按钮名称的闭包方法,然后在有效负载中添加该名称。 / p>

closureFunction(btnName){
   dispatch({
      ...dispButtonEnter,
      payload:{name: btnName}
   })
}

在reducer中,您将能够访问action参数中的有效负载。