簡體   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