【问题标题】:When use useEffect, I get a warning when passing less than variable dependency使用 useEffect 时,我在传递小于变量依赖项时收到警告
【发布时间】:2021-10-27 17:40:35
【问题描述】:

在我的 React 应用程序中,我有一个 redux 存储,其中包含具有以下模型的弹出状态:

stateFilter: {
    visible: false
  }

在我的页面上,我得到了商店中弹出窗口的状态:

const mapStateToProps = ({ list }) => ({
  visible: list.stateFilter.visible
});

我想查询数据库以使用状态变量进行过滤。 而且我只想在弹出窗口关闭时运行我的操作中的功能。 为此,我利用了 useEffect 钩子:

  useEffect(() => {
    if (!visible) {
      search({
        start: min,
        end: max
      })
    }
  }, [visible])

我在名为“搜索”的 redux 操作中的操作。 而 'min', 'max' 是在操作弹窗时改变的状态变量。

当执行应用程序时,我收到如下警告:

React Hook useEffect has missing dependencies: 'max', 'min', and 'search'. Either include them or remove the dependency array. If 'search' changes too often, find the parent component that defines it and wrap that definition in useCallback

如果我传递了所有依赖项,则警告会关闭,但是当最小值、最大值发生变化时,我会看到我的 函数持续运行

我尝试像这样使用 useCallback:

  const filter = useCallback(() => {
    search({
      start: min,
      end: max
    })
  })

  useEffect(() => {
    if (!visible) {
      filter();
    }
  }, [visible, filter])

然后我又收到这样的警告:

React Hook useCallback does nothing when called with only one argument. Did you forget to pass an array of dependencies?

当警告出现时,表示某些东西没有优化,但我不知道处理这种情况的最佳方法是什么。

那么在这种情况下实现useEffect的正确方法是什么?

【问题讨论】:

  • 持续运行可能意味着您有一个逻辑错误,即设置 min 或 max 或随后的搜索调用最终会导致 min 或 max 或另一个导致再次触发的依赖项发生变化。你需要找到那个循环并打破它。如果您在无限循环的版本上发布更多内容,也许我可以提供更明确的建议

标签: reactjs react-hooks use-effect


【解决方案1】:

你必须添加依赖数组

const filter = useCallback(() => {
    search({
      start: min,
      end: max
    })
  }, [search, min, max])

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2021-09-04
    • 2019-12-14
    • 2021-08-13
    • 1970-01-01
    • 2020-05-28
    • 2020-11-21
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多