addEventListener react redux with mapped dispatch

2019-06-21 20:32发布

问题:

I am currently trying to add an event listener to an application I'm making in react. I'm doing this by hooking into the componentDidMount API, which runs only once the component is rendered and not more than that. My problem is that I'm using connect from react-redux to bind my action creators to store.dispatch. I'm not sure how to bind the event listener to the version of the action creator that is bound to the store with dispatch. Is there a graceful way to do this?

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:

Simply get it from 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 );
  }

I believe you also need to unsubscribe from the keydown event on component unmount event though. (even if it does not do that ever, just for sake of completeness and robustness).



标签: reactjs redux