【问题标题】:Action invoked without dispatching it - Redux动作调用而不调度它 - Redux
【发布时间】:2019-04-25 07:25:57
【问题描述】:

我正在尝试了解 redux,但对 mapDispatchToProps 有一些疑问。

代码如下。

import * as actions  from '../../redux/actions';
import './style.scss'

class Center extends Component {
  componentDidMount() {
    this.props.getCenters();
  }

  ...
}
export default connect(state => ({
  ...state.center,
}),{
  ...actions,
})(Center);

Actions 文件定义如下。

export const getCenters = () => ({
  type: types.CENTERS_REQUEST,
});

当组件被挂载时, this.props.getCenters() 被调用并且动作被调度并且一切都按预期工作。

问题是,

getCenters 的定义中没有提到 dispatch。那么,如何在不分派的情况下调用此操作?

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    Redux 将 dispatch(隐式)注入到您在 connect 中的操作中:

    export default connect(state => ({
      ...state.center,
    }),{
      ...actions,
    })(Center);
    

    如果我们稍微抽象一下,我们可以观察它是如何发生的(显式地):

    function mapDispatchToProps(dispatch) {
        return {
            getCenters: () => dispatch(getCenters())
        }
    }
    
    export default connect(state => ({
      ...state.center,
    }), mapDispatchToProps)(Center);
    

    因此,getCenters 配备了dispatch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2021-10-14
      • 1970-01-01
      • 2017-05-19
      • 2020-09-10
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多