addEventListener 对 redux 与映射分派做出反应
addEventListener react redux with mapped dispatch
我目前正在尝试将事件侦听器添加到我在 React 中制作的应用程序。我通过连接到 componentDidMount API 来做到这一点,它 只运行一次 组件被渲染并且不会超过那个。我的问题是我正在使用 react-redux
中的 connect
将我的动作创建者绑定到 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);
只需从 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
事件。 (即使它从来没有这样做过,只是为了完整性和稳健性)。
我目前正在尝试将事件侦听器添加到我在 React 中制作的应用程序。我通过连接到 componentDidMount API 来做到这一点,它 只运行一次 组件被渲染并且不会超过那个。我的问题是我正在使用 react-redux
中的 connect
将我的动作创建者绑定到 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);
只需从 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
事件。 (即使它从来没有这样做过,只是为了完整性和稳健性)。