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

gar*_*rds 5 reactjs redux

我目前正在尝试将一个事件监听器添加到我正在做出反应的应用程序中.我这样做是通过挂钩componentDidMount API来实现的,该API 在呈现组件时运行,而不是更多.我的问题是,我使用connectreact-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);
Run Code Online (Sandbox Code Playgroud)

zer*_*kms 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 );
  }
Run Code Online (Sandbox Code Playgroud)

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