【发布时间】:2014-11-09 17:21:22
【问题描述】:
Facebook Flux 调度程序explicitly prohibits ActionCreators from dispatching other ActionCreators。这种限制可能是个好主意,因为它会阻止您的应用程序创建事件链。
但是,一旦您的 Store 包含来自相互依赖的异步 ActionCreators 的数据,这就会成为一个问题。如果CategoryProductsStore 依赖于CategoryStore,则似乎没有办法在不推迟后续操作的情况下避免事件链。
场景 1: 包含某个类别中的产品列表的商店需要知道它应该从哪个类别 ID 获取产品。
var CategoryProductActions = {
get: function(categoryId) {
Dispatcher.handleViewAction({
type: ActionTypes.LOAD_CATEGORY_PRODUCTS,
categoryId: categoryId
})
ProductAPIUtils
.getByCategoryId(categoryId)
.then(CategoryProductActions.getComplete)
},
getComplete: function(products) {
Dispatcher.handleServerAction({
type: ActionTypes.LOAD_CATEGORY_PRODUCTS_COMPLETE,
products: products
})
}
}
CategoryStore.dispatchToken = Dispatcher.register(function(payload) {
var action = payload.action
switch (action.type) {
case ActionTypes.LOAD_CATEGORIES_COMPLETE:
var category = action.categories[0]
// Attempt to asynchronously fetch products in the given category, this causes an invariant to be thrown.
CategoryProductActions.get(category.id)
...
场景 2:
另一种情况是,由于 Store 更改及其componentWillMount/componentWillReceivePropsattempts to fetch data via an asynchronous ActionCreator,而挂载了子组件:
var Categories = React.createClass({
componentWillMount() {
CategoryStore.addChangeListener(this.onStoreChange)
},
onStoreChange: function() {
this.setState({
category: CategoryStore.getCurrent()
})
},
render: function() {
var category = this.state.category
if (category) {
var products = <CategoryProducts categoryId={category.id} />
}
return (
<div>
{products}
</div>
)
}
})
var CategoryProducts = React.createClass({
componentWillMount: function() {
if (!CategoryProductStore.contains(this.props.categoryId)) {
// Attempt to asynchronously fetch products in the given category, this causes an invariant to be thrown.
CategoryProductActions.get(this.props.categoryId)
}
}
})
有没有办法避免这种情况而不诉诸延迟?
【问题讨论】:
-
对于场景#1,我将这种逻辑放在动作创建者自己中,这样存储只响应数据的变化。在存在异步逻辑的情况下,动作创建者有时会将多个动作分派到商店。我遇到了场景 #2,要么切换到
DidMount(在异步数据加载的情况下),要么偶尔推迟到setTimeout。 -
@BrandonTilley 我已经澄清了这两个示例,在这两种情况下,用于获取类别中产品的 ActionCreator 都会触发异步 API 操作。
-
@SimenBrekken 你的问题解决了吗?请问stackoverflow.com/questions/32537568/…可以看这里吗?
标签: reactjs reactjs-flux