简体   繁体   English

在 useEffect 上使用方法有困难,缺少依赖项和 useCallback 错误?

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

This is my code:这是我的代码:

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

I have this error:我有这个错误:

React Hook useEffect has a missing dependency: 'dfEventQuery'. React Hook useEffect 缺少依赖项:'dfEventQuery'。 Either include it or remove the dependency array包括它或删除依赖项数组

but when i add it on the array: [shopWelcomeSent, history, dfEventQuery] I get this error:但是当我将它添加到数组中时:[shopWelcomeSent, history, dfEventQuery] 我收到这个错误:

The 'dfEventQuery' function makes the dependencies of useEffect Hook (at line 201) change on every render. 'dfEventQuery' 函数使 useEffect Hook(第 201 行)的依赖项在每次渲染时发生变化。 To fix this, wrap the 'dfEventQuery' definition into its own useCallback() Hook要解决此问题,请将 'dfEventQuery' 定义包装到它自己的 useCallback() 钩子中

I've been stuck with it for hours and just can't wrap my head why this don't work?我已经坚持了几个小时,只是无法理解为什么这不起作用?

so in this case it's easier just to wrap function into useCallback listing all its dependencies there:所以在这种情况下,将函数包装到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]);

and listing it into useEffect 's dependencies.并将其列出到useEffect的依赖项中。

But honestly, I'd expect Eslint not complaining on missing dependency since in your code it will be recreated in relevant render cycle and no "stale closure" issue will happen anyway.但老实说,我希望 Eslint 不会抱怨缺少依赖项,因为在您的代码中,它将在相关的渲染周期中重新创建,并且无论如何都不会发生“过时的关闭”问题。

[UPD] find similar case in thread https://github.com/facebook/react/issues/14920#issuecomment-467212561 but don't see any comment either if that's expected(and why) or if it's legit to have such a function out of useEffect's deps. [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