【问题标题】:Making clean double successive axios requests with React/redux使用 React/redux 进行干净的双连续 axios 请求
【发布时间】:2026-01-06 13:20:06
【问题描述】:

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

我设法使用以下代码axios(postOptions) 然后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() 函数:

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))
      });
  }
}

重用这个函数可能会更好,但是当getItems() 函数在addItem() 函数内部调用时,它永远不会进入dispatch() 内部。

你能帮我找出问题所在吗?

非常感谢。

【问题讨论】:

  • 尝试像这样在 dispatch(getItems()) 中调用 getItems

标签: reactjs redux axios


【解决方案1】:

getItems 是一个 redux action,需要在 dispatch 中调用

dispatch(getItems())

【讨论】: