[英]how to prevent multiple function call in react js on value change
我想防止對用戶操作進行多次 function 調用。在我的演示應用程序中,我有一個TABS和輸入字段。 我想在用戶TAB 更改時調用 function,當用戶在輸入字段上鍵入任何內容時調用相同的 function。當用戶更改選項卡時也重置輸入字段值。
問題是當我更改選項卡時,我的 function 被調用了兩次。 為什么? 我認為這僅是由於 setState。
這是我的代碼https://codesandbox.io/s/sleepy-leaf-pi3ykn?file=/src/App.tsx
const AsyncCall = () => {
console.log("AsyncCallAsyncCallAsyncCallAsyncCall");
};
React.useEffect(() => {
console.log("init");
AsyncCall();
}, [value, textValue]);
React.useEffect(() => {
console.log("reset value");
setTextValue("");
}, [value]);
重現步驟
有什么辦法可以預防。 我嘗試使用ref對我沒有用
我想在每次文本字段值更改和選項卡更改時調用 function。 但是當用戶更改 Tab 時我需要重置文本字段值還有什么建議嗎?
您可以像這樣在 TextField onChange 中調用異步調用
onChange={(e) => { setTextValue(e.target.value); AsyncCall(); }}
並且可以在 Tabs onChange 中重置你的值
handleChange = (event: React.SyntheticEvent, newValue: number) => { setValue(newValue); setTextValue(""); }
擺脫 useEffect 它們在這里是不必要的
根據您的需要
我想在每次文本字段值更改和選項卡更改時調用 function。 但是當用戶更改 Tab 時,我還需要重置文本字段值
讓我們看看您的代碼中的問題。
React.useEffect(() => {
console.log("init");
AsyncCall();
}, [value, textValue]);
當每個值和 textValue 更改時,您的 useEffect 都會調用。 如果我們在您的 valueChange 方法中調用AsyncCall()
方法,我們可以刪除此 useEffect。
對於文本字段
const handleTextChange = () => {
setTextValue(e.target.value);
AsyncCall();
}
<TextField
id="outlined-basic"
onChange={handleTextChange} // i name it handleTextChange
value={textValue}
label="Outlined"
variant="outlined"/>
現在,每當您要更改 textValue 時,它都會調用AsyncCall()
方法。
對於選項卡
const handleChange = ()=>{
setValue(newValue);
// resetting text value as you want to reset it on tab change
setTextValue("");
// Calling AsyncCall() on Tab menu change
AsyncCall();
}
<Tabs
value={value}
onChange={handleChange}
aria-label="basic tabs example"
>
</Tabs>
現在,不需要這些 useEffects
React.useEffect(() => {
console.log("init");
AsyncCall();
}, [value, textValue]);
React.useEffect(() => {
console.log("reset value");
setTextValue("");
}, [value]);
建議:對於 textValue,您可以使用 De-bounce 技術來避免不必要的重新渲染https://www.freecodecamp.org/news/debouncing-explained/
將此代碼粘貼到您的handleChange
方法中
setValue(newValue);
setTextValue("")
並刪除你的第二個useEffect()
鈎子
React.useEffect(() => {
console.log("reset value");
setTextValue("");
}, [value]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.