我想对自定义输入进行去抖,但我的问题是我无法在初始渲染时停止触发器中的 useEffect
import { useDebouncedCallback } from "use-debounce";
interface myInputProps {
getValue: any;
}
const MyInput = ({ getValue }: myInputProps) => {
const [value, setValue] = useState("");
React.useEffect(() => {
getValue(value);
}, [value]);
return (
<input type="text" value={value} onChange={e => setValue(e.target.value)} />
);
};
export default function App() {
const [debouncedCallback] = useDebouncedCallback(value => {
console.log(value);
}, 1000);
return (
<div className="App">
<MyInput getValue={debouncedCallback} />
</div>
);
}
https://codesandbox.io/s/upbeat-lamport-ukq70?file=/src/App.tsx
我也尝试过 useLayoutEffect
但它没有解决问题。
最佳答案
我们可以使用 useRef 来跟踪 useEffect 钩子(Hook)是否是第一次运行。
https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
沙盒链接:https://codesandbox.io/s/confident-cerf-flkf2?file=/src/App.tsx
const MyInput = ({ getValue }: myInputProps) => {
const [value, setValue] = useState("");
const first = useRef(true);
React.useEffect(() => {
if (first.current) {
first.current = false;
return;
}
getValue(value);
}, [value]);
return (
<input type="text" value={value} onChange={e => setValue(e.target.value)} />
);
};
关于javascript - 防止 useEffect 在初始渲染时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61135815/