【发布时间】: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