首页 > 解决方案 > 无法执行 React 状态更新 - 反应手势库

问题描述

在尝试了不同的解决方案之后,包括推荐的方法Can't perform a React state update on an unmounted component似乎没有什么能解决我的问题。

编辑:我注意到这仅发生在第一次渲染后的第一次渲染上,我没有收到任何错误

我在我的组件中使用 react-gesture-gallery,如下所示:

return (
    <CardsContainer>
      <Gallery
        style={{
          background: "linear-gradient(to bottom, #FFFFFF,#5643fa )"
        }}
        index={index}
        onRequestChange={ i => setIndex(i)}
      >
        <SingleSwipeCard
          handleClick={() => startDefaultGame()}
          text={practiceSavedWordsText}
        />
       <SingleSwipeCard
          handleClick={() => startDefinitionGame()}
          text={practiceCompletingSentences}
        />
      <SingleSwipeCard
          handleClick={() => startGrammerGame()}
          text={practiceTypingWordsText}
        />
    </Gallery>
   </CardsContainer>
)

我有 3 个SingleSwipeCard组件,现在我希望动画自动播放,所以我的 useEffect 钩子看起来像这样:

 useEffect(() => {
    console.log("did mount");

    timer = setInterval(() => {
      if (index === 2) {
        setIndex(0);
      } else setIndex(index + 1);
    }, 8000);

    return () => {
      console.log("un mount");
      clearInterval(timer);
    };
  }, [index, gameStarted]);

动画按预期工作,但问题是我的handleClick功能正在将用户重定向到应用程序中的另一个页面,所以我得到了Can't perform a React state update on an unmounted component....

虽然组件似乎没有在页面路由功能之后呈现,并且在最后一次呈现时调用了 cleanUp 函数,但这里缺少一些东西并且我遇到了内存泄漏。

标签: javascriptreactjsasynchronous

解决方案


推荐阅读