在 redux 中调度不同的操作

Dispatch different actions in redux

本文关键字:操作 调度 redux      更新时间:2023-09-26

我有一个(React)容器组件。它的孩子需要来自不同 api 端点的不同数据,所以我想同时调度 2 个操作(两者都是异步的)。

这似乎是不可能的。如果我有两个调度,activeSensors总是空的......

class Dashboard extends React.Component {
  static propTypes = {
    userData: React.PropTypes.array.isRequired,
    activeSensors: React.PropTypes.object.isRequired
  };
  static contextTypes = {
    store: React.PropTypes.object
  };
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    const { store } = this.context;
    store.dispatch(fetchActiveSensorDataForAllSensors());
    store.dispatch(fetchUserData());
  }
  render() {
    return (
      <div>
        <AnalyticsPanel activeSensors={this.props.activeSensors}/>
        <SearchCustomer userData={this.props.userData}/>
      </div>
    );
  }
}
export default connect((state)=> {
  return {
    userData: state.userData.data,
    activeSensors: state.activeSensorsAll.sensors
  }
})(Dashboard);

编辑:请参阅完整组件的来源。

我没有使用您的代码使用的this.context.store.dispatch方法,但我认为它不一定是您应该做事的方式。主要是因为它确实混淆了容器和表示组件之间的界限。表示组件不需要访问store,并且还有其他方法可以做到这一点,这些方法没有这个(尽管迂腐)缺点。

我的组件文件通常如下所示:

import React from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';
export class Container from React.Component {
  componentWillMount() {
    // Most conical way
    const { fetchActiveSensorDataForAllSensors, fetchUserData } = this.props;
    fetchActiveSensorDataForAllSensors();
    fetchUserData();
    // Less conical way
    // const { dispatch } = this.props;
    // const { fetchActiveSensorDataForAllSensors, fetchUserData } = actions;
    // dispatch(fetchActiveSensorDataForAllSensors());
    // dispatch(fetchUserData());
  }
  render() {
    return (
      <div>
        <AnalyticsPanel activeSensors={this.props.activeSensors}/>
        <SearchCustomer userData={this.props.userData}/>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    activeSensors: state.activeSensorsAll.sensors,
    userData: state.userData.data
  }
}
export default connect(mapStateToProps, actions)(Container);