【问题标题】:Dispatch different actions in redux在 redux 中调度不同的动作
【发布时间】:2016-02-08 15:12:10
【问题描述】:

我有一个 (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);

编辑:查看完整组件的源代码。

【问题讨论】:

  • 您需要在示例中提供更多代码。您发布的内容应该可以使用 - 您的 connect 是什么样的?你们的减速机在做什么?等

标签: javascript redux redux-thunk


【解决方案1】:

我没有使用您的代码使用的this.context.store.dispatch 方法,但我认为这不一定是您应该做的事情。主要是因为它确实混淆了container and presentational components 之间的界限。展示组件不需要访问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);

【讨论】:

  • 查看我的编辑,我已经添加了完整的组件。唯一不同的是,我没有将调度操作解析到 connect 中的组件(我不需要这样做)
  • 我更新了我的答案以修复我复制了你的代码但没有更新它的地方;查看对componentWillMount 的更改。这应该可以工作——如果没有,您需要确认您的操作确实像您认为的那样触发,然后确定它们的减速器是否正确更新了状态对象。我还编辑了我的 actions 导入/连接,因此不存在范围冲突。
  • 好的,这可行,但请解释为什么可行。为什么我需要解析连接函数的动作?
  • 这是Dan自己描述过的一种方式。看这里。 egghead.io/lessons/…
  • 哇哦,谢谢分享。我从未在示例或 GH 问题上看到过这一点。很高兴知道。不过,我不确定为什么它目前不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2021-01-29
  • 2021-09-11
  • 1970-01-01
相关资源
最近更新 更多