【发布时间】:2015-08-02 19:48:51
【问题描述】:
ReactJS 我想我明白了,但 Flux 让我感到困惑。我觉得现在最简单的任务需要成倍增加的代码和复杂性。
我正在尝试使用图表和列表报告一些数据。我创建的是一个“WindowStore”,它包含代表报告期(默认为一天)的“开始”和“结束”时间。我在组件中有按钮,可以一次向前和向后移动一小时。
在组件的 render() 方法中,我返回这个(作为更大组件的一部分):
<button onClick={this.stepBack} type="button"
className="btn btn-default btn-xs"
disabled={this.state.loading}>
<i className="fa fa-angle-double-left fa-2x"></i>
</button>
我的组件中有这个处理程序:
stepBack: function() {
WindowActions.stepBack();
}
WindowActions.stepBack 向 WindowStore 发送消息以更新开始和结束值:
stepBack: function() {
Dispatcher.dispatch({type: WindowConstants.Actions.STEP_BACK});
}
WindowStore 捕获 STEP_BACK 并将开始和结束值递减 1 小时。它发出一个更改事件,组件使用新的状态“开始”和“结束”值更新图形边界。
我有第二个存储,它记录图表的数据,GraphStore。数据通过 AJAX 调用填充到 GraphActions 中的服务器,理想情况下使用 WindowStore 中的开始和结束值(注意:我删除了错误处理):
refresh: function(start, end) {
Api.getGraphData(start, end, function(reply) {
Dispatcher.dispatch({
type: GraphConstants.Actions.Refresh,
results: reply.data
});
});
}
我可以在 componentDidMount() 中调用 refresh() 以在开始时更新图形:
getInitialState: function() {
return {
window: WindowStore.getState(),
graph: GraphStore.getState()
}
},
componentDidMount: function() {
GraphActions.refresh(this.state.window.start, this.state.window.end);
}
这是我的心理障碍:然后我想做的是在窗口移动时刷新数据。我应该如何/在哪里打这个电话?我觉得我的图形组件应该在状态发生变化时调用 GraphActions.refresh() ,但这显然是一个调度链,所以不行。我能找到的唯一选择是让 WindowActions.stepBack 调用 GraphActions.refresh。但这意味着我必须传入新的开始值和结束值,并将 GraphActions 紧密耦合到 WindowActions:
stepBack: function(start, end) {
Dispatcher.dispatch({type: WindowConstants.Actions.STEP_BACK});
GraphActions.refresh(start, end);
}
这是对的吗?当我想更新从同一个 WindowStore 绘制的列表组件或其他图形组件时,我该怎么办?我也应该在 stepBack 中调用它们吗?如果我需要 GraphActions.refresh() 加载的数据并且我想等待刷新完成怎么办?这感觉耦合太紧密和混乱。
请帮忙。
【问题讨论】:
-
可以分享你的组件源代码和窗口商店源代码
-
实现
waitFor函数或使用通量库waitFor。 facebook.github.io/flux/docs/dispatcher.html#content