【问题标题】:React Hook useCallback has an unnecessary dependency: 'price'. Either exclude it or remove the dependency array react-hooks/exhaustive-depsReact Hook useCallback 有一个不必要的依赖:'price'。排除它或删除依赖数组 react-hooks/exhaustive-deps
【发布时间】:2019-07-06 16:15:43
【问题描述】:
import React, {Fragment, useState,useCallback } from "react";

const ProcessingSearch = () => {
  const [price, setPrice] = useState({ maxPrice: 0, minPrice: 0 });

  const inputMaxMin = useCallback(
    ({ target: { value, name } }) => {
      name === "maxPrice"
        ? setPrice(({ minPrice }) => ({ maxPrice: value, minPrice }))
        : setPrice(({ maxPrice }) => ({ minPrice: value, maxPrice }));
    },
    [price]
  );

  return (
    <Fragment>
      <form onSubmit={() => {}}>
        {"Min"}
        <input
          {...ProcessingSearchInputPrice}
          value={price.minPrice}
          onChange={inputMaxMin}
        />
        {"Max"}
        <input
          {...ProcessingSearchInputPrice}
          value={price.maxPrice}
          onChange={inputMaxMin}
        />
        <input type="submit" title={"Submit price range"} value={"Go"} />
      </form>
    </Fragment>
  );
};

当我使用价格时出现错误:

React Hook useCallback 有一个不必要的依赖:'price'。要么排除 它或删除依赖数组 react-hooks/exhaustive-deps

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这是对useCallback 实施的警告(不是因为price 的使用)。

    如警告所述,从依赖数组 [price] 中删除 price 变量:

    const inputMaxMin = useCallback(
        ({ target: { value, name } }) => {
          name === "maxPrice"
            ? setPrice(({ minPrice }) => ({ maxPrice: value, minPrice }))
            : setPrice(({ maxPrice }) => ({ minPrice: value, maxPrice }));
        },
       []                 // <--- remove price, not used within the hook.
      );
    

    在这种情况下,我相信您可以删除useCallback 的使用,因为您不记忆任何内容,请查看示例。

    【讨论】:

    • setPrice 不应该作为依赖项。
    • 是的,在这种情况下,不需要回调吧?
    • useCallback 没有依赖项 ([]) 应该可以工作
    • 我认为它可以防止&lt;input&gt; fron 重新渲染......虽然这只是一个非常轻微的改进。
    • 为什么不同样适用于useEffect 钩子? react-hooks/exhaustive-deps 没有警告我在以下示例中不需要 valueWhichMayChange(第 13 行)-> codesandbox.io/s/react-example-ey9pw?file=/index.js
    【解决方案2】:

    我不明白为什么 screens 不需要作为依赖项以及为什么我必须删除它们。

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2021-10-21
      • 1970-01-01
      • 2021-07-15
      • 2021-12-06
      • 2020-06-09
      • 2021-10-31
      • 2023-01-15
      • 1970-01-01
      相关资源
      最近更新 更多