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

Edg*_*gar 4 reactjs

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>
  );
};
Run Code Online (Sandbox Code Playgroud)

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

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

Den*_*ash 5

这是对实施的警告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.
  );
Run Code Online (Sandbox Code Playgroud)

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

编辑检查渲染