简体   繁体   中英

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>
  );
};

When I use price I get an error:

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

Its a warning for useCallback implementation (not because of price usage).

As the warning states, remove price variable from the dependencies array [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.
  );

In this case, I believe you can remove the use of useCallback because you don't memoize anything, check the example.

编辑检查如果渲染

I can't figure out why screens are not needed as dependency and why I have to remove them.

编辑 dazzling-kapitsa-d0i9d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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