简体   繁体   中英

React missing dependency warning when I don't want it to depend

I have a similar warning to this one , however I don't want the value it wants me to add in the dependency array, so should I suppress the warning?

I have an array and an index which are both stored as state in a component. I want to have a useMemo hook to update a value every time the index changes, based off the value in the array that the index is pointing to. I don't want it update when the array changes, so I only have the index in the array of dependencies. Is there a way to get around this without suppressing the warning?

There's a few ways you can do this, without seeing your code it's hard to say which will work best for you. Assuming your component looks something like this:

const MyComponent = () => {
  const [values, setValues] = useState<number[]>([0]);
  const [index, setIndex] = useState(0);

  // Calculate the value as 10x whatever the number is at index:
  // WARNING - missing dependency
  const calculatedValue = useMemo(
    () => 10 * values[index],
    [index]);

  return (
    // ...
  );

You could use a ref to keep track of the values, and then use that in your callback:

const valuesRef = useRef<number[]>(values);
valuesRef.current = values;

const calculatedValue = useMemo(
  () => 10 * valuesRef.current[index],
  [index]);

But a better solution, if you only want to change the calculated value when the index changes, is handle the calculation in the callback:

const runCalculation = (value: number) => 10 * value;

const MyComponnet = () => {
  const [values, setValues] = useState<number[]>([0]);
  const [index, setIndex] = useState(0);
  const [calculatedValue, setCalculatedValue] = useState<number>(
    () => runCalculation(values[index])
  );

  const handleChangeIndex = (nextIndex: number) => {
    setIndex(nextIndex);
    setCalculatedValue(runCalculation(values[nextIndex]));
  };

  return (
    // ...
  );
};

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