【问题标题】:How to call an action that return dispatch function using React Hook?如何使用 React Hook 调用返回调度函数的操作?
【发布时间】:2021-07-21 17:11:17
【问题描述】:

我同时使用 React Class 和 Hooks。我知道我不应该,但你知道公司的遗留代码是如何工作的。我们正在走向钩子,但这需要时间和精力。我们正在使用 redux thunk。在分页呈现用户时,我们有如下操作:

action.js 文件:

export const fetchAccounts = (page, countPerPage)=>{
  return function (dispatch){
    dispatch(fetchAccountsInit());
    return axiosInstance.get(`/auth/users/fetch-users/${page}/${countPerPage}`)
     .then(res => res.data)
     .then(accounts=>{
         dispatch(fetchAccountsSuccess(accounts));
         return accounts
      })
     .catch(({response}) => {
     dispatch(fetchAccountsFail(response.data.errors));
  })

} }

之前的开发者是这样的: 使用钩子的 User.js 文件:

const getUserList = () => {    
  dispatch(actions.fetchAccounts(page, countPerPage))
  .then(res => {  
      setUsers(res);
      setCountPerPage(10);
      setTotalRows(res[0].total_count);
  }).catch(err => {
    setUsers({});
  });
}

useEffect(() => {
  getUserList();
}, [page]);

代码运行没有问题。但在我看来,这似乎是不对的。我相信代码应该是:

export const fetchAccounts = (page, countPerPage)=>{
  return function (dispatch){
     dispatch(fetchAccountsInit());
     axiosInstance.get(`/auth/users/fetch-users/${page}/${countPerPage}`)
       .then(res => res.data)
       .then(accounts=>dispatch(fetchAccountsSuccess(accounts)))
       .catch(({response}) => {
           dispatch(fetchAccountsFail(response.data.errors));
       })
  }
}

当我调用const getUserList = () => { ... 时,上面的函数相同 我收到错误TypeError: Cannot read property 'then' of undefined

目前正在运行的 User.js 文件中没有 mapDispatchToProps。它使用import {useDispatch} from 'react-redux';const dispatch = useDispatch(); 我想我不明白如果改变动作,这个分页应该如何工作。我正在工作的这个项目中的代码是正确的还是有问题?

【问题讨论】:

    标签: reactjs redux react-hooks redux-thunk


    【解决方案1】:

    在您进行更改之前,thunk 正在返回最终数据的承诺 - 您删除了 return,现在它返回 undefined。如果你想做一个dispatch(thunk()).then(...),那个thunk 仍然需要返回一个promise。

    【讨论】:

    • 那么在更改动作之后调用“const getUserList()”内部的调度函数的方法是什么,以便我可以链接“then”。我应该打电话给dispatch(thunk(actions.fetchAccounts(page, countPerPage))).then(...)
    • 是的,这是可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2018-07-16
    • 2017-12-27
    • 2018-05-06
    相关资源
    最近更新 更多