简体   繁体   English

mapDispatchToProps与store.dispatch()

[英]mapDispatchToProps vs. store.dispatch()

Is it more efficient to use mapDispatchToProps inside a component to call actions or is it more efficient to use store.dispatch inside action creators? 在组件内部使用mapDispatchToProps来调用动作更有效, store.dispatch在动作创建者内部使用store.dispatch更有效?

mapDispatchToProps example: mapDispatchToProps示例:

// Component

import React from 'React';
import { connect } from 'react-redux';
import { defaultAction } from './actions';

class MyComponent extends Component {
  onClickHandler() {
    this.props.dispatch(defaultAction());
  }

  render() {
    return (<div onClick={this.onClickHandler.bind(this)} />);
  }
}

function mapDispatchToProps(dispatch) {
  return { dispatch };
}

export default connect(mapDispatchToProps)(MyComponent);



// Actions

import { DEFAULT_ACTION } from './constants';

export function defaultAction() {
  return {
    type: DEFAULT_ACTION,
  };
}

store.dispatch() example: store.dispatch()示例:

// Component

import React from 'React';
import { connect } from 'react-redux';
import { defaultAction } from './actions';

class MyComponent extends Component {
  onClickHandler() {
    defaultAction();
  }

  render() {
    return (<div onClick={this.onClickHandler.bind(this)} />);
  }
}

export default MyComponent;


// Actions

import { DEFAULT_ACTION } from './constants';
import store from './store';

export function defaultAction() {
  store.dispatch({
    type: DEFAULT_ACTION,
  });
}

My guess is that it's more efficient to use mapDispatchToProps instead of importing the entire ./store to dispatch actions. 我的猜测是,使用mapDispatchToProps而不是导入整个./store来调度动作会更有效。

It is generally recommended to use dispatch as provided to you via mapDispatchToProps , and not to couple your action creator methods to your store singleton. 通常建议使用dispatch作为通过提供给您mapDispatchToProps ,而不是你的情侣创造者行动的方法来你的店单。 Here's some in depth discussion about it. 这里是有关它的一些深入讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM