簡體   English   中英

如何防止多個 function 調用響應 js 值更改

[英]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]); 


 

重現步驟

  1. Run Application AsyncCall function call only 一次
  2. 在輸入字段示例“abc”中鍵入一些文本。 每次調用 function都是正確的行為
  3. 清除控制台日志
  4. 切換第二個選項卡。 如果您看到AsyncCall function 調用兩次。 我只需要打電話一次。 不是兩次。這是錯誤。 當用戶切換標簽時,我也需要重置輸入字段

有什么辦法可以預防。 我嘗試使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM