nextjs 中的“react-router-dom”中的 {useLocation} 是否有等效项

Tem*_*odu 12 javascript reactjs next.js

import { useLocation } from 'react-router-dom';

我目前正在使用 Nextjs,我需要类似useLocation的帮助

`

 import Link from 'next/link';
 import { FC } from 'react';
 import {useRouter} from 'next/router';
 import { useStore } from '../store';`



const PrivateRoute: FC = ({ children }) => {
const currentUser = useStore((state) => state.currentUser);
const location = useRouter();`

if (!currentUser)
    return (
        <Link
            href={`/sign-in?redirect=${encodeURIComponent(
                location.pathname + location.push('chat')
            )}`}
        />
    );
return <>{ children }</>
Run Code Online (Sandbox Code Playgroud)

}

导出默认私有路由;`

Blo*_*gic 7

导航

const router = useRouter()
const navigateTo = () => router.push('/dashboard/app')
Run Code Online (Sandbox Code Playgroud)

路径名

const router = useRouter()
console.log(router.pathname); // logs the current pathname
Run Code Online (Sandbox Code Playgroud)

获取上一页的状态

页A:

const router = useRouter()
router.push({
  pathname: '/B',
  query: { result: JSON.stringify(result) }
});
Run Code Online (Sandbox Code Playgroud)

B页:

const router = useRouter()
let result = JSON.parse(router.query.result);
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用“next/router”中的 useRouter,然后可以使用路径名或 asPath,然后有条件地添加 slug 或参数。其余的,您可以通过其他人发布的文档找到更多信息。