繁体   English   中英

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

[英]React Hook useCallback has an unnecessary dependency: 'price'. Either exclude it or remove the dependency array react-hooks/exhaustive-deps

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

它是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的使用,因为您不会useCallback任何内容,请查看示例。

编辑检查如果渲染

我无法弄清楚为什么不需要screens作为依赖项以及为什么我必须删除它们。

编辑 dazzling-kapitsa-d0i9d

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM