You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo Router导航无法阻止useEffect重复触发问题求助

Expo Router导航无法阻止useEffect重复触发问题求助

嘿,我现在在做一个用Expo开发的React Native应用,碰到个useEffect的问题卡壳了,想请教下大家!

我写的useEffect代码片段是这样的:

useEffect(() => {
  const updateGameData = async () => {
    if (!game) return;

    if (isLastStep && !isLastRound) {
      const nextRound = game.currentRound + 1;

      if (nextRound > game.totalRound) {
        router.replace("/home");
        return;
      }

      setGame({
        ...game,
        currentRound: nextRound,
        // 后续还有更新游戏数据的逻辑
      });
    }
  };

  updateGameData();
}, [game, isLastStep, isLastRound]); // 这里是我设置的依赖数组

问题是:当满足nextRound > game.totalRound的条件时,我明明调用了router.replace("/home")跳转到首页了,可这个useEffect还是会重复触发,导致后面的setGame逻辑又跑了一遍,直接打乱了整个游戏流程。我本来以为跳转之后当前组件会立刻卸载,useEffect就不会再执行了,结果完全不是这么回事…

我自己琢磨了几个可能的解决方向,想问问大家是不是靠谱:

  • 给useEffect加个卸载标记:组件卸载时标记一下,这样就算跳转后还有未完成的逻辑,也能中断后续操作,避免不必要的状态更新
useEffect(() => {
  let isUnmounted = false;

  const updateGameData = async () => {
    if (!game || isUnmounted) return;

    if (isLastStep && !isLastRound) {
      const nextRound = game.currentRound + 1;

      if (nextRound > game.totalRound) {
        router.replace("/home");
        return;
      }

      if (!isUnmounted) {
        setGame({
          ...game,
          currentRound: nextRound,
        });
      }
    }
  };

  updateGameData();

  return () => {
    isUnmounted = true;
  };
}, [game, isLastStep, isLastRound, router]);
  • 检查依赖数组是不是有问题:会不会是我漏加了某个依赖,或者多加了导致组件频繁重渲染,进而触发useEffect?
  • 是不是Expo Router的replace方法不是同步生效的?跳转需要一点时间,这时候组件还没卸载,依赖项变化就又触发了useEffect?

有没有朋友碰到过类似的坑?或者有其他更优雅的解决办法吗?麻烦支个招!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 13:59:33