【发布时间】:2021-07-28 10:00:19
【问题描述】:
我在这里发现了许多关于 React Hook useEffect 缺少依赖项的类似问题。我已经检查过它们,但我没有找到我所面临的解决方案。我想将 redux thunk function 作为参数传递给 React custom hook。
下面是我的代码,它工作正常。但是,我得到了依赖缺失警告,我不想添加 ignore warning eslint。如果我将 dispatchAction 添加到依赖数组列表中,它会一次又一次地调度,因为 redux thunk asyn 函数已经完成,拒绝,挂起。
自定义挂钩
const useFetchData = (dispatchAction, page) => {
const dispatch = useDispatch();
const [loadMoreLoading, setLoadMoreLoading] = useState(false);
const [errorMsg, setErrorMsg] = useState();
useEffect(() => {
const fetchData = async () => {
setLoadMoreLoading(true);
const resultAction = await dispatch(dispatchAction);
if (resultAction.meta.requestStatus === 'rejected') {
setErrorMsg(resultAction.payload.message);
}
setLoadMoreLoading(false);
};
fetchData();
}, [dispatch, page]);
return [loadMoreLoading, errorMsg]; // it is asking for adding dispatchAction.
我的组件
const SomeListing = ({userId}) => {
const [page, setPage] = useState(1);
const [loadMoreLoading, errorMsg] = useFetchData(
fetchPropertyByUserId({userId: userId, page: page}),
page,
);
}
那么,有什么方法可以在 react 自定义钩子中添加 redux thunk 函数?
【问题讨论】:
标签: reactjs react-hooks redux-thunk