在 redux 中调度不同的操作
Dispatch different actions in redux
我有一个(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);
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- Redux-正确调度操作
- reactJs redux:如何对用户事件调度操作并将操作与化简器和存储链接
- 我可以在没有 Redux Thunk 中间件的情况下调度多个操作吗?
- 如何从不知道 Redux 的服务调度操作
- 在 redux 中调度不同的操作
- 具有新状态的 Redux 调度操作和化简器
- 如果正在调度操作,是否会调用每个 Redux 缩减器
- 反应/Redux 应用程序操作未正确调度
- 我如何从我的API模块调度一个redux操作?
- 在Redux不工作的情况下调度操作,得到未捕获的typeError,说它不是一个函数
- 调度操作创建器语法react-redux
- 如何在redux-thunk中断言在异步操作内部调度的异步操作
- 在特定日期时间调度操作
- push()即使我推送相同的url也会调度LOCATION_CHANGE操作
- 如何在使用Redux进行异步操作调度后检索状态数据
- 如何从存储本身获取在存储上调度的最后一个操作类型
- React-Router:为什么 组件的 onClick 处理程序不会调度我的操作
- Redux thunk:从调度操作中返回承诺
- Redux:根据交叉化简器状态调度操作