簡體   English   中英

在Redux中調度不同的動作

[英]Dispatch different actions in redux

我有一個(反應)容器組件。 它的孩子需要來自不同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方法,但是我認為它不一定是您應該做的事情。 主要是因為它確實混淆了容器和表示組件 s之間的界限。 表示性組件不需要訪問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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM