在 React 中获取删除请求后,函数不会发送 Redux Dispatch

Function won't send Redux Dispatch after a Fetch Delete Request in React

我向后端 onClick 提交删除请求,当我从服务器收到响应时,我尝试调用调度函数来更新 Redux 存储。后台数据可以有效删除请求;然而,当我包含调度调用时,React 给我这个错误:

  ./src/actions/questions.js
  Line 68:  'dispatch' is not defined  no-undef

我已经尝试了很多不同的语法和 .then 收到响应后的组合,但没有任何效果。这让我感到困惑,因为在我进行的 thunk fetch 调用中,我可以在收到响应时调用 dispatch。我无法使用传统的 thunk 语法,因为它不会触发请求,因为它最初是在组件的 onClick 事件中触发的。所以,我发出的删除获取请求看起来像这样:

 export function deleteQuestion(questionId, routerHistory) {
     return fetch(`${API_URL}/questions/${questionId}`, {
         method: 'DELETE',
     }).then(res => 
     dispatch(removeQuestion(questionId)))
   }

我曾考虑过在方法之外调度 removeQuestion,但后来我担心 Redux 存储会与后端数据不同步并在以后引起问题。我将不胜感激任何人可以提供的任何见解。我不认为删除项目和更新 Redux 商店应该如此具有挑战性。

这也是github:https://github.com/jwolfe890/react_project1/blob/master/stumped-app-client/src/actions/questions.js

再次感谢。

您的语法错误。 thunk 将 return 一个接受 dispatch 作为参数的函数。 dispatch 会被中间件传入。因此,您的动作创建者应如下所示:

export function deleteQuestion(questionId, routerHistory) {
  return (dispatch) => {
    fetch(`${API_URL}/questions/${questionId}`, {
      method: 'DELETE',
    }).then(res => {
      dispatch(removeQuestion(questionId))
    })
  }
}

看到问题出在您的 deleteQuestion 函数中,您既没有定义 dispatch 是什么,也没有将 dispatch 作为参数传递给您的函数。所以你收到错误 dispatch is not defined

redux-thunk 中,您 return 一个以 dispatch 作为参数的函数,由 redux-thunk 中间件提供。这就是它运行良好的原因。