使用React/redux进行两次连续的axios请求的清理 [英] Making clean double successive axios requests with React/redux

查看:56
本文介绍了使用React/redux进行两次连续的axios请求的清理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要发出axios post 请求以更新列表,然后发出axios get 请求以获取更新的列表.

I need to make an axios post request to update a list and then an axios get request to fetch the updated list.

我设法使用以下代码进行这些操作: axios(postOptions)然后是 axios(getOptions):

I managed to do these operations with the following code axios(postOptions) then axios(getOptions):

export function addItem() {
  ...
  return dispatch => {
    axios(postOptions)
      .then(response => {
        dispatch({
          type: ITEM_ADDED,
          payload: response.data
        });
        // getItems(); // <= unfortunately, this doesn't work, so I repeat some code
        axios(getOptions)
          .then(response => {
            dispatch({
              type: ITEMS_FETCHED,
              payload: response.data
            });
          })
          .catch(error => {
          return dispatch(handleError(error))
          });
      })
      .catch(error => {
        return dispatch(handleError(error))
      });
}

该代码有效,但是我重复我自己,因为我已经有了此 getItems()函数:

The code works but I repeat myself as I already have this getItems() function:

export function getItems() {
  ...
  return dispatch => {
    console.log('I am here') // <= when getItems() is inside addItem() function, 'I am here' is never displayed.
    axios(options)
      .then(response => {
        dispatch({
          type: ITEMS_FETCHED,
          payload: response.data
        });
      })
      .catch(error => {
        return dispatch(handleError(error))
      });
  }
}

重用此函数可能会更好,但是在 addItem()函数内部调用 getItems()函数时,它永远不会在内部dispatch().

It could have been better to reuse this function but when the getItems() function is called inside the addItem() function, it never goes inside the dispatch().

请问您能帮我找出问题出在哪里吗?

Can you help me to figure out what is going wrong please ?

非常感谢.

推荐答案

getItems是一个redux操作,您需要在dispatch中调用它

getItems is a redux action, you need to call it in dispatch

dispatch(getItems())

这篇关于使用React/redux进行两次连续的axios请求的清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆