reactjs - 我如何更新商店页面加载第一次反应挂钩?
问题描述
我只是一个新手反应钩子,所以我有一个这样的案例:
const [lessonStore, updateLessonStore] = useLessonStore();
const fetchLessons = async () => {
updateLessonStore(draft => {
draft.filter = {
limit: TABLE.defaultLimit,
page: 1,
courses: values,
};
});
console.log(lessonStore)
const res = await getLessons(lessonStore.filter);
if (res) {
switch (res.status) {
case httpStatus.OK: {
setData(res.data);
break;
}
case httpStatus.UNAUTHORIZED: {
resetRefreshTokenFailure();
break;
}
default:
break;
}
}
};
useEffect(() => {
fetchLessons();
}, [lessonStore.filter.limit, lessonStore.filter.page,lessonStore.filter.courses]);
我有两个问题,希望有人能解释一下:
在 console.log 中,为什么 courseStore 中的课程没有值?(值是数组 id)
如何在 useEffect 中的 courseStore.filter.courses 中不呈现无限循环?
对不起我的英语不好,谢谢。
解决方案
在 console.log 中,为什么 courseStore 中的课程没有值?(值是数组 id)
- 状态更新是异步的。该
fetchLessons
值来自闭包(即先前的值)。
如何在 useEffect 中的 courseStore.filter.courses 中不呈现无限循环?
- useEffect 在
lessonStore.filter.courses
加上其他依赖项发生更改时执行。在 useEffect 中,您正在更新lessonStore.filter.courses
,因此最终会出现无限循环。您可以lessonStore.filter.courses
从依赖项数组中删除。
推荐阅读
- java - How to convert sorted Arraylist to BST
- r - 从R中的交叉引用表中获取最后一个值
- heroku - Heroku 平台积分
- c - 与 C 中的 Java NextInt 类似的功能
- acumatica - 当 DeletedDatabaseRecord 为真时,用户可以查看记录吗?
- ios - IOS/Objective-C:在 SharedInstanceSingleton 中清除 ivars 或属性值的最佳方法
- r - 根据索引条件分配值矩阵
- selenium - “Chrome 无法启动:异常退出”
- python - Tkinter 的子窗口下存在无法解除父窗口?(Python 3.6.6,Windows 7 旗舰版)
- android - 查询获取 Json 的 vimeo 文件问题