最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Hydration error when wrapping useSearchParams with Suspense - Stack Overflow

programmeradmin0浏览0评论

I used useSearchParams not wrapped in Suspense, but now I need ISR and I was getting build errors saying I should wrap every component using useSearchParams in Suspense.

Now that I wrapped it I am getting hydration error:

Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch to client rendering. The usual way to fix this is to wrap the original update in startTransition.

Do you have an idea on how to fix?

This is the code:

export function useFullPathWithLocale(): FullPathWithLocale | null {
  const pathname = usePathnameWithLocale();
  const searchParams = useSearchParams();
  return getFullPath(pathname, searchParams);
}

function LanguageSelectorInternal(props: LanguageSelectorProps) {
  const { chooseLabel, onChange } = props;
  const currentFullPathnameWithLocale = useFullPathWithLocale();
  const { currentLocale } = useLocale();

  const router = useRouter();

  function handleChange(locale: NextLocale) {
    if (!currentFullPathnameWithLocale) {
      return;
    }

    const alternateLinks: HTMLAnchorElement[] = Array.from(document.querySelectorAll('head link[hrefLang]'));
    const altLangHref = alternateLinks.find((x) => x.hreflang === locale)?.href;
    const altLangFullPath = brandOptionalString<'FullPathWithLocale'>(
      altLangHref ? convertHrefToFullPath(altLangHref) : undefined,
    );

    const redirectHref = altLangFullPath ?? replaceLocaleInFullPath(currentFullPathnameWithLocale, locale);

    if (typeof onChange === 'function') {
      onChange();
    }

    router.push(redirectHref);
  }

  const chooseLabelSr = chooseLabel ? <span className={css.sr}>{chooseLabel}</span> : null;

  return (
    <div>
      <Select onChange={e => handleChange(e.currentTarget.value)}>
        ...
      </Select>
    </div>
  );
}

export function LanguageSelector(props: LanguageSelectorProps) {
  return (
    <Suspense>
      <LanguageSelectorInternal {...props} />
    </Suspense>
  );
}
发布评论

评论列表(0)

  1. 暂无评论