addEventListener 使用映射调度对 redux 做出反应 [英] addEventListener react redux with mapped dispatch

查看:42
本文介绍了addEventListener 使用映射调度对 redux 做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试向我正在制作的应用程序添加一个事件侦听器.我是通过挂钩到 componentDidMount API 来实现的,该 API 只运行一次 组件被呈现,并且不会更多.我的问题是我使用 react-redux 中的 connect 将我的动作创建者绑定到 store.dispatch.我不确定如何将事件侦听器绑定到通过调度绑定到商店的动作创建者的版本.有没有优雅的方法来做到这一点?

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);

推荐答案

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

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).

这篇关于addEventListener 使用映射调度对 redux 做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆