2016-01-20 22 views
3

我有一个更新Redux中的某些搜索条件的操作。我想立即从基于本地标准的API获取一些数据。问题是,虽然搜索条件动作分派是同步的,但在搜索结果分派开始之前它不会完成。如何在Redux中完成另一个同步操作时分派操作

在这个例子中,该标准将不会在API调用之前更新:

this.props.dispatch(updateLocalCriteria(someData)); 
this.props.dispatch(fetchApiResults(this.props.criteria)) 

我失去了一些东西明显?我可以想到一些简单的方法来处理这个问题,但最好的方法是什么?我应该在搜索条件更新时设置一个标志,并且如果标志为真,则在componentDidUpdate()中获取结果?或者我应该使updateLocalCriteria()异步,以便我可以在承诺链中链接fetchApiResults()

编辑

我想我已经找到了我的答案。我可以在fetchApiResults()之内获得当前状态。因此,我可以在进行api调用之前获取当前的搜索条件。

function fetchApiResults() { 
    return (dispatch, getState) => { 
     const state = getState(); 
     // fetch data and dispatch... 

回答

1

在你updateLocalCriteria,你可能已经改变你减速的道具之一,以新的价值,我会打电话给它criteria

你可以做的反而是创建另一个行动让我们说updateCriteriaAndFetch将被调用就像你一样:

this.props.dispatch(updateCriteriaAndFetch(newCriteria)) 

,你将基本定义,像这样

export const updateCriteriaAndFetch = criteria => dispatch => { 
    dispatch(updateLocalCriteria(criteria)) 
    dispatch(fetchApiResults(criteria)) 
} 

第二调度会甚至等待第一次同步更新完成,即使您不需要它,因为您已经可以访问它。

你仍然可以做你刚刚说的,得到你的商店的当前状态,但是对我来说这看起来相当矫枉过正,因为你可以简单地将它作为参数或你的行为传递。

+0

'updateLocalCriteria()'只更新条件的一个属性,但我想将所有条件发送到'fetchApiResults()'。我想在调用'fetchApiResults()'之前,我仍然需要在'updateCriteriaAndFetch()'中获取当前状态。 –

+0

在这种情况下是的 –