首页 > 解决方案 > 我如何更新商店页面加载第一次反应挂钩?

问题描述

我只是一个新手反应钩子,所以我有一个这样的案例:

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]);

我有两个问题,希望有人能解释一下:

对不起我的英语不好,谢谢。

标签: reactjsreact-hooks

解决方案


在 console.log 中,为什么 courseStore 中的课程没有值?(值是数组 id)

  • 状态更新是异步的。该fetchLessons值来自闭包(即先前的值)。

如何在 useEffect 中的 courseStore.filter.courses 中不呈现无限循环?

  • useEffect 在lessonStore.filter.courses加上其他依赖项发生更改时执行。在 useEffect 中,您正在更新lessonStore.filter.courses,因此最终会出现无限循环。您可以lessonStore.filter.courses从依赖项数组中删除。

推荐阅读