export function useSyncHistory()

in packages/react/react-portal/src/utils.ts [92:124]


export function useSyncHistory(history: History) {
  const { path, syncHistory, __innerStamp, __historyState } = useContext(Context).appProps || {};
  // 上一次同步的 path
  const prevSyncPath = useRef('');
  const innerStamp = useRef('');
  const isFirstEnter = useRef(true);

  // 主子应用 path 不同或开启同步路由时,需要同步
  // 开启路由同步时,强制更新路由 updateHistory,避免微应用内部路由改变后,主应用再次跳转初始路径时不生效
  const needSync = (prevSyncPath.current !== path && path) || syncHistory;
  // render 是否是由主应用触发,需要主应用在 props 传递 __innerStamp
  // 如果是主应用触发,一定会传递 __innerStamp,兼容历史逻辑:__innerStamp 可能不存在
  const renderFromParent = typeof __innerStamp === 'undefined' || (__innerStamp && innerStamp.current !== __innerStamp);

  // 注意同步路由发生在第一次 mount 后
  useEffect(() => {
    // innerStamp 没有变化,说明更新不是由主应用触发,跳过路由同步逻辑
    if (needSync && renderFromParent) {
      prevSyncPath.current = path;
      innerStamp.current = __innerStamp;
      updateHistory(history, path, __historyState);
    }

    isFirstEnter.current = false;
  });

  return {
    isFirstEnter: isFirstEnter.current,
    needSync,
    renderFromParent,
    syncHistory,
  };
}