addEventListener 使用映射调度对 redux 做出react

IT技术 reactjs redux
2021-05-02 14:44:03

我目前正在尝试向我正在制作的应用程序添加一个事件侦听器。我是通过挂钩到 componentDidMount API 来实现的,该 API在组件呈现后运行,并且此之后运行我的问题是我正在使用connectfromreact-redux将我的动作创建者绑定到store.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个回答

只需从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组件卸载事件的事件。(即使它从来没有这样做,只是为了完整性和健壮性)。