从react-router-dom转换到NextJS

ar5n3qh5  于 2023-06-29  发布在  React
关注(0)|答案(2)|浏览(164)

我不知道如何在NextJS中使用他们的路由器API而不是react-router-dom来复制它。

import { Route, Redirect } from "react-router-dom";
import auth from "../../services/authService";

const ProtectedRoute = ({ path, component: Component, render, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => {
        if (!auth.getCurrentUser())
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location }
              }}
              j
            />
          );
        return Component ? <Component {...props} /> : render(props);
      }}
    />
  );
};

export default ProtectedRoute;

这是这样使用的:

<ProtectedRoute path="/form/:id" component={Form} />
s5a0g9ez

s5a0g9ez1#

根据Next.js文档,您最好使用Link而不是React-router-dom或任何其他路由器。

vyu0f0g1

vyu0f0g12#

如果你认为你可以重构你的组件来达到你想要的结果:
(使用nextjs v13和page router,注意app router router.replace不接受相同的参数)
(注意:我删除了一些参数:“休息”,“ prop ”,并改变了“组件”/“渲染”的孩子)

import auth from "../../services/authService";
import { useRouter } from "next/navigation";

const ProtectedRoute = ({ path, children }) => {
  // This is an equivalent to react-router useNavigate()
  const router = useRouter();

  if (!auth.getCurrentUser()) {
    router.replace({ pathname: "/login", query: { from: props.location }});
    return null;
  }

  // user is auth, we render the component
  return children;
};

export default ProtectedRoute;

相关问题