简体   繁体   中英

Dispatch different actions in redux

I have a (React) container component. It's children need different data from different api endpoints, so I want to dispatch 2 actions the same time (both are asynchronous).

This doesn't seem to be possible. If I have both dispatches, the activeSensors are always empty...

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

EDIT: See the source for the full component.

I haven't used the this.context.store.dispatch method your code uses, but I don't think that its necessarily the way you should be doing things. Primarily because it really muddies the line between container and presentational component s. Presentational components don't need access to store , and there are other methods to do this which don't have this (albeit pedantic) drawback.

My component files typically look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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