我们如何从 Next.js 应用程序获取 window.location.hash?

geo*_*yws 16 next.js

如果我们坚持window.location.hash下去useEffect,它总是会错误地返回“0”。显然这与SSR有关。

我需要能够可靠地获取我的项目的 URL 的哈希部分。我应该怎样做才最好呢?

Sea*_*n W 15

服务器端代码需要等待代码加载到浏览器中才能使用浏览器 API。

Vanilla js 服务器端兼容

const [isMounted, setMounted] = useState(false);
  
useEffect(() => {
 if (isMounted) {
  console.log('hash', window.location.hash);
 } else {
  setMounted(true);
 }
}, [isMounted]);

if(!isMounted) return <>Loading...</>;
Run Code Online (Sandbox Code Playgroud)

使用下一个/路由器

import { useRouter } from 'next/router';

const { asPath } = useRouter();

useEffect(()=>{
 const hash = asPath.split('#')[1];
}, [ asPath ]);
Run Code Online (Sandbox Code Playgroud)

仅供参考,您的代码不应返回零。第一个想到的罪魁祸首是在没有 else 的情况下使用简写条件。

window && window.location.hash
Run Code Online (Sandbox Code Playgroud)

这应该有一个 else

(window && window.location.hash) || null
Run Code Online (Sandbox Code Playgroud)

或者

window && window.location.hash ? window.location.hash : null
Run Code Online (Sandbox Code Playgroud)

  • 据我所见,哈希值未包含在 router.asPath 中 (4认同)