NextJS 13类型错误:router.events未定义,next/navigation已导入

50few1ms  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(150)

我尝试使用最新的nextjs 13,next/router替换为next/navigation来显示Loading text while the route is loading the url state

"use client";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import axios from "axios";

const Header = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false); 
  const router = useRouter();

  useEffect(() => {
    const handleStart = () => {
      setIsLoading(true); 
    };

    const handleComplete = () => {
      setIsLoading(false); 
    };

    router.events.on("routeChangeStart", handleStart);
    router.events.on("routeChangeComplete", handleComplete);

    return () => {
      router.events.off("routeChangeStart", handleStart);
      router.events.off("routeChangeComplete", handleComplete);
    };
  }, [router]);

  const handleFormSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true); 

    try {
      const response = await axios.get(`/result?search_query=${encodeURIComponent(searchQuery)}`);
      const data = response.data;

      console.log("Search Results:", data);

      router.push(`/result?search_query=${encodeURIComponent(searchQuery)}`);
    } catch (error) {
      console.log("Error:", error);
    } finally {
      setIsLoading(false); 
    }
  };

  const handleInputChange = (e) => {
    setSearchQuery(e.target.value);
  };

  return (
    {/* Render data */}
  );
};

export default Header;

使用next/router给出错误:未装载NextRouter。
我的文件在app/components/Header.jsx中,切换到客户端到pages/Header.jsx也不行

jhkqcmku

jhkqcmku1#

我遇到了同样的问题
router.events 在Next.js上已不存在13
在git上快速搜索找到了一些帮助
https://github.com/vercel/next.js/discussions/42016?sort=new
希望这能有所帮助

相关问题