我目前正在尝试向我正在制作的应用程序添加一个事件侦听器。我是通过挂钩到 componentDidMount API 来实现的,该 API仅在组件呈现后运行,并且仅在此之后运行。我的问题是我正在使用connect
fromreact-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);