【问题标题】:How to dispatch an action when another synchronous action is complete in Redux如何在 Redux 中完成另一个同步操作时分派一个操作
【发布时间】:2016-04-25 15:51:11
【问题描述】:

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

在本例中,条件在 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...

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    在您的 updateLocalCriteria 中,您可能已经将 reducer 的一个 props 更改为新值,我将其命名为 criteria

    你可以做的是创建另一个动作,比如说updateCriteriaAndFetch,它会像你一样被调用:

    this.props.dispatch(updateCriteriaAndFetch(newCriteria))
    

    你基本上会这样定义

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

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

    你仍然可以照你说的做,获取你商店的当前状态,但对我来说这似乎有点过头了,因为你可以简单地将它作为参数或你的操作传递。

    【讨论】:

    • updateLocalCriteria() 只是更新标准的一个属性,但我想将所有标准发送到fetchApiResults()。我想我仍然需要在调用fetchApiResults() 之前获取updateCriteriaAndFetch() 中的当前状态。
    • 在这种情况下确实是的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多