如何使用react-router-dom在next js中更改页面

mftmpeh8  于 2023-06-22  发布在  React
关注(0)|答案(2)|浏览(194)

如果登录成功,我想更改页面,但我收到此错误消息:

用这个代码:

export default function SignUp() {
  const trigger = async (event: any) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const navigate = useNavigate();
    try {
      const response = await fetchRestEndpoint(`/users`, 'POST', {
        username: data.get("username"),
        email: data.get("email"),
        password: data.get("password"),
        role: "user"
      });
    if (response.ok) {
      const user: any = await response.json();
      console.log(user);
      navigate('/');
    }
  } catch(e) {
    alert(e);
  }
  ......
qlfbtfca

qlfbtfca1#

Next.js提供了自己的路由器。您不需要使用react-router-dom。我强烈建议你看看related documentation

使用pages目录时
import { useCallback } from "react";
import { useRouter } from "next/router";

const MyComponent = () => {
  const router = useRouter();

  const login = useCallback(() => {
    // ...
    router.push("/some-url")
  }, [router]);

  return (
    // ...
  );
}
使用app目录时
import { useCallback } from "react";
import { useRouter } from "next/navigation";

const MyComponent = () => {
  const router = useRouter();

  const login = useCallback(() => {
    // ...
    router.push("/some-url")
  }, [router]);

  return (
    // ...
  );
}
bqjvbblv

bqjvbblv2#

问题是,通过从回调函数调用React钩子,你打破了钩子的规则。React钩子只能在顶层调用,例如在React函数组件的主体中,或自定义React钩子。
useNavigate钩子移出回调。

export default function SignUp() {
  const navigate = useNavigate(); // <-- call in function body

  const trigger = async (event: any) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);

    try {
      const response = await fetchRestEndpoint("/users", "POST", {
        username: data.get("username"),
        email: data.get("email"),
        password: data.get("password"),
        role: "user"
      });

      if (response.ok) {
        const user: any = await response.json();
        console.log(user);
        navigate('/');
      }
    } catch(e) {
      alert(e);
    }

  ...

相关问题