react-hooks/exhaustive-deps的疑问?

作者站长头像
站长
· 阅读数 25
const [searchValue, setSearchValue] = useState({
    age: undefined,
    name: undefined,
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
  });
  const getList = useCallback(
    () => {
      setLoading(true);
      queryList({
        age: searchValue.age,
        name: searchValue.name,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
      }).then().catch().finally(() => setLoading(false));
    },
    [pagination.current, pagination.pageSize, searchValue.age, searchValue.name],
  );

上面的代码,提示

React Hook useCallback has a missing dependency: 'pagination'. Either include it or remove the dependency array. Mutable values like 'pagination.current' aren't valid dependencies because mutating them doesn't re-render the component.eslintreact-hooks/exhaustive-deps

但是我的代码中使用了pagination.current和pagination.pageSize,而且依赖项中也显性的写了这两个值

为什么提示要依赖pagination?

怎么才能让他检测的更准确些呢?

回复
1个回答
avatar
test
2024-07-14

翻了下源码,是因为你的属性名为current,换个名字就行了,比如pagination.pageNo

应该是考虑到开发者把ref放到deps里面的情况。

源码地址

=====以下为原答案===

提示里不是说的很清楚的了么

Mutable values like 'pagination.current' aren't valid dependencies because mutating them doesn't re-render the component.

如果你写了类似下面这种代码

pagination.current = 100

useCallback里的函数并不会得到更新。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容