簡體   English   中英

在 useEffect 上使用方法有困難,缺少依賴項和 useCallback 錯誤?

[英]Having difficulty using a method on useEffect, missing dependency and useCallback error?

這是我的代碼:

  const dfEventQuery = async (event: string) => {
    const {
      data: { result }
    } = await axios.post("/api/df_event_query", { event, userId });
    for (let msg of result.fulfillmentMessages) {
      const botSay: MessageDataType = { speaks: "bot", msg };
      setMessages(oldMessages => [...oldMessages, botSay]);
    }
  };
  const resolveInXSeconds = (x: number) =>
  new Promise(res => {
    setTimeout(() => {
      res(x);
    }, x * 1000);
  });
  useEffect(() => {
    dfEventQuery("Welcome");
    if (inputRef.current) inputRef.current.focus();
    const sendShopWelcome = async () => {
      await resolveInXSeconds(1);
      dfEventQuery("WELCOME_SHOP");
      setShopWelcomeSent(true);
      setShowChatbot(true);
    };
    if (window.location.pathname === "/shop" && !shopWelcomeSent) {
      sendShopWelcome();
    }
    history.listen(() => {
      if (history.location.pathname === "/shop" && !shopWelcomeSent) {
        sendShopWelcome();
      }
    });
  }, [shopWelcomeSent, history]);

我有這個錯誤:

React Hook useEffect 缺少依賴項:'dfEventQuery'。 包括它或刪除依賴項數組

但是當我將它添加到數組中時:[shopWelcomeSent, history, dfEventQuery] 我收到這個錯誤:

'dfEventQuery' 函數使 useEffect Hook(第 201 行)的依賴項在每次渲染時發生變化。 要解決此問題,請將 'dfEventQuery' 定義包裝到它自己的 useCallback() 鈎子中

我已經堅持了幾個小時,只是無法理解為什么這不起作用?

所以在這種情況下,將函數包裝到useCallback更容易,在useCallback列出它的所有依賴項:

const dfEventQuery = useCallback(async (event: string) => {
  const {
    data: { result }
  } = await axios.post("/api/df_event_query", { event, userId });
  for (let msg of result.fulfillmentMessages) {
    const botSay: MessageDataType = { speaks: "bot", msg };
    setMessages(oldMessages => [...oldMessages, botSay]);
  }
}, [userId]);

並將其列出到useEffect的依賴項中。

但老實說,我希望 Eslint 不會抱怨缺少依賴項,因為在您的代碼中,它將在相關的渲染周期中重新創建,並且無論如何都不會發生“過時的關閉”問題。

[UPD] 在線程https://github.com/facebook/react/issues/14920#issuecomment-467212561 中找到類似的案例,但如果這是預期的(以及為什么),或者是否合法擁有這樣一個在 useEffect 的 deps 之外運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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