如何停止再次调用useEffect(附代码)

85 阅读1分钟

容器

import { InputField } from './InputField';

const sleep = (time: number) => new Promise((res) => setTimeout(res, time, ''));

export const Container = () => {
  const [inputValue, setInputValue] = React.useState('');

  React.useEffect(() => {
    (async () => await sleep(1000))();
    async function fetchMyAPI(time, value) {
      await sleep(time);
      setInputValue(value);
    }
    fetchMyAPI(1000, 'vbc1');
    fetchMyAPI(2000, 'dgi1');
  }, []);

  const inputChange = (value) => {
    setInputValue(value);
  };

  return <InputField inputValue={inputValue} inputChange={inputChange} />;
};

输入字段

export const InputField = ({
  inputValue,
  inputChange,
}: {
  inputValue: string;
  inputChange: (value: string) => void;
}) => {
  const [value, setValue] = React.useState('');

  React.useEffect(() => {
    setValue(inputValue.slice(0, -1));
  }, [inputValue]);

  const handleChange = (event) => {
    setValue(event.target.value);
    inputChange(event.target.value + '1');
  };

  return <input value={value} onChange={handleChange} />;
};

上面的inputValue可以多次变化。另外,input中的一个局部变量是用来显示的,而inputValue与它略有不同。所以当我们跟踪InputValue时,我们把清除的数据传递给局部变量。反之亦然,我们修改数据放到inputValue中。

  React.useEffect(() => {
    setValue(inputValue.slice(0, -1));
  }, [inputValue]);

每次我们改变InputValue,我们就会改变局部变量,但在我们调用inputChange时,它已经包含了正确的值。而这就是问题所在!

这个问题的正确解决方案是什么?