redux中的异步问题

在redux的异步场景中遇到这个问题。

场景是这样:

我需要通过 redux-thunk 来发两个 api 请求。
但是第一个请求的返回数据正是第二个请求的请求数据,所以必须等第一个请求返回了才能发起第二个请求。

怎么解决这样的问题?

阅读 5.7k
5 个回答

模拟个例子,createTodo发起网络请求,返回后发起另一个请求。

function createTodo (todo) {
  return (dispatch) => {
    fetch('/todos/create', {})
    .then(result => {
      dispatch({type: 'CREATED', result})
      dispatch(getTodo(result.id))
    })
  }
}

function getTodo (id) {
  return (dispatch) => {
    fetch(`/todos/${id}`, {})
    .then(result => {
      dispatch({type: 'LOADED', result})
    })
  }
}

感觉这种情况可以直接使用 promise-middleware 中间件,可以直接这样写:

// 假设你有两个 action 发送请求:fetchInfo, fetchDetail

dispatch(fetchInfo())
    .then((action) => {
        // action.payload 就是 fetchInfo 的请求数据
        return dispatch(fetchDetail());
    })
    .then((action) => {
        // action.payload 就是 fetchDetail 的请求数据
    })

为什么不用await

。。这跟redux没关系吧,你用promise就好了呗

function createTodo (todo) {
  return (dispatch) => {
    return fetch('/todos/create', {})
    .then(result => {
      dispatch({type: 'CREATED', result})
    })
  }
}

function getTodo (id) {
  return (dispatch) => {
    return fetch(`/todos/${id}`, {})
    .then(result => {
      dispatch({type: 'LOADED', result})
    })
  }
}
也可以createTodo().then(if(state==='成功!') getTodo())
由于then无论成功失败都会执行。fetch 尿性。所以dispatch后需要判断你改变的state满足了需求,说明createTodo 执行成功了,就执行下一个
这种情况当两个方法不在同一文件中,或者还会跟随者其他的操作的时候用
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题