reactjs Nextjs显示“NextRouter was not mounted”错误[重复]

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

此问题已在此处有答案

NextRouter was not mounted Next.JS(7个回答)
3天前关闭。
在这段代码中,我试图获取input的值,并试图将其重定向到'/search/${searchvalue}',其中'searchvalue'是input的值。然而,每当我尝试这样做时,我都会得到一个错误,说'Error: NextRouter was not mountedhttps://nextjs.org/docs/messages/next-router-not-mounted'

"use client"
import { useState } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';

export default function Navbar() {
  const [searchValue, setSearchValue] = useState('');
  const router = useRouter();

  const handleSearch = (e) => {
    e.preventDefault();
    router.push(`/search/${searchValue}`);
  };

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

  return (
    <div id="navbarComp">
      <div id="navbar">
        <Link href="/">
          <div id="explore">
            <h1>Explore</h1>
          </div>
        </Link>
      </div>
      <div id="inputsearch">
        <form onSubmit={handleSearch}>
          <input
            className="dog"
            placeholder="Search"
            value={searchValue}
            onChange={handleInputChange}
          />
        </form>
      </div>
    </div>
  );
}

我尝试了多种选择,似乎没有一个奏效。

kokeuurv

kokeuurv1#

算了,我想出来了。
下面是工作代码

"use client"
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function Navbar() {
  const [searchValue, setSearchValue] = useState('');
  const router = useRouter();

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

  const handleSearch = (e) => {
    e.preventDefault();
    router.push(`/search/${searchValue}`);
  };

  return (
    <div id="navbarComp">
      <div id="navbar">
        <Link href="/">
          <div id="explore">
            <h1>Explore</h1>
          </div>
        </Link>
      </div>
      <div id="inputsearch">
        <form onSubmit={handleSearch}>
          <input
            className="dog"
            placeholder="Search"
            value={searchValue}
            onChange={handleInputChange}
            onSubmit={() => router.push(`/search/${searchValue}`)}
          />
        </form>
      </div>
    </div>
  );
}
von4xj4u

von4xj4u2#

尝试将输入事件对象传递给handleInputChange,如下所示:

...

<input
 className="dog"
 placeholder="Search"
 value={searchValue}
 onChange={(e)=> handleInputChange(e)}
/>

...

相关问题