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

ee7vknir  于 2023-03-11  发布在  Java
关注(0)|答案(3)|浏览(123)

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 }</>

}
导出默认的私有路由;'

wlzqhblo

wlzqhblo1#

你可以从'next/router'使用useRouter,然后你可以使用pathname或asPath,然后你有条件地添加slug或params。其余的你可以通过其他人发布的文档找到更多的信息。

dwbf0jvd

dwbf0jvd2#

导航

const router = useRouter()
const navigateTo = () => router.push('/dashboard/app')

路径名

const router = useRouter()
console.log(router.pathname); // logs the current pathname

从上一页获取状态

A页:

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

第B页:

const router = useRouter()
let result = JSON.parse(router.query.result);
np8igboo

np8igboo3#

是的您可以在react-router-dom v6中使用useNavigate,也可以在react-router-dom〈v6中使用useHistory

相关问题