【发布时间】:2021-10-28 20:35:15
【问题描述】:
我开始学习 Redux 和 thunk 库。
我有一个包含函数的 Actions.js:
export const fetchInventory = (user_id) => {
return (dispatch) => {
dispatch(fetchInventoryData());
fetch("url", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
//make sure to serialize your JSON body
body: JSON.stringify({ user_id }),
})
.then((res) => res.json())
.then((res) => {
saveInventory(res);
dispatch(fetchInventorySuccess(res));
})
.catch((err) => dispatch(fetchInventoryFailure(err)));
};
};
和一个带有useEffect的Container.js如下:
useEffect(() => {
if (inventory.inventoryData.length > 0) return;
else if (user_id) fetchInventory(user_id);
else return [];
}, [user_id]);
EsLint 警告我在依赖数组中缺少 fetchInventory 和 inventory。但是,由于库存是此获取将更新的状态,包括它会使我们陷入无限获取。此外,这里需要的 user_id 是来自之前的获取请求的东西。在这种情况下,什么会进入依赖数组,为什么?
【问题讨论】:
标签: reactjs redux react-hooks use-effect redux-thunk