addEventListener将redux与映射调度进行反应

时间:2016-02-03 23:28:14

标签: reactjs redux

我目前正在尝试将一个事件监听器添加到我正在做出反应的应用程序中。我通过连接到componentDidMount API来执行此操作,该API只运行一次呈现组件,而不是更多。我的问题是,我使用connect中的react-redux将我的动作创建者绑定到store.dispatch。我不确定如何将事件侦听器绑定到使用dispatch绑定到存储的动作创建者的版本。有没有一种优雅的方式来做到这一点?

import React, {PropTypes} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import GridApp from '../components/GridApp';
import * as GridActions from '../actions/gridActions';

class App extends React.Component {
  render() {
    const { gridAppState, actions } = this.props;
    return (
        <GridApp gridAppState={gridAppState} actions={actions} />
    );
  }
  componentDidMount() {
    console.log("mounted")
    // the following line won't be bound to the store here...
    document.addEventListener("keydown", GridActions.naiveKeypress );
  }
}

function mapStateToProps(state) {
  return {
    gridAppState: state.gridAppState
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(GridActions, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

1 个答案:

答案 0 :(得分:3)

只需从this.props

获取
  componentDidMount() {
    console.log("mounted")
    // the following line won't be bound to the store here...

    const { actions } = this.props;
    document.addEventListener("keydown", actions.naiveKeypress );
  }

我相信您还需要取消订阅有关组件卸载事件的keydown事件。 (即使它没有这样做,只是为了完整性和稳健性)。