如何在Next.js中访问查询?

pkmbmrz7  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(119)

我在Next.js中有两个组件。(假设<Navbar /><SearchResult />。)
<Navbar />有一个搜索栏,用户可以在其中搜索项目,还有一个搜索按钮,点击后会将用户重定向到显示结果的<SearchResult />页面。<Navbar />组件允许我发送搜索到的查询,但我不能在<SearchResult />组件中捕获它。
//我可以在url-bar(localhost:3000/searchresult?query=somequery)中看到查询,但当我尝试在控制台中记录时,它显示undefined
下面是我的<Navbar />的代码片段:

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

const NavBar = () => {

    const router = useRouter()

    const [searchQuery, setSearchQuery] = useState('')

    const handleSearch = async (e: React.FormEvent) => {
      e.preventDefault()
      
        setSearchQuery(searchQuery)

        //redirect the user to searchresults page
        router.push(`/searchresults?query=${searchQuery}`)
      }

      return (<Navbar className="bg-transparent">
          <NavbarItem className="bg-white rounded-md" >
            <input 
              type="text" 
              className="outline-none text-black p-2 text-small rounded-l-md"
              placeholder="Search for a Character"
              value={searchQuery}
              onChange={(e)=> setSearchQuery(e.target.value)}/>
            <button 
              className="text-black px-2 hover:text-emerald-400 transition-colors"
              type="submit"
              onClick={handleSearch}>Search</button>
          </NavbarItem>
        </NavbarContent>
      </Navbar>)
}

export default NavBar

这是我的<SearchResult />组件的代码:

'use client'

import { useRouter } from "next/navigation"

const page = ({params} : {params: any}) => {
  const router = useRouter()

  const { searchQuery } = useParams()

  console.log(searchQuery)

    return (
      <div>
         Hello..
      </div>
    )
  }

export default page

我到处都找过了,但似乎找不到解决办法。救命啊!

qltillow

qltillow1#

我相信你正在寻找useSearchParams。

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function SearchBar() {
  const searchParams = useSearchParams()
 
  const query = searchParams.get('query')
 
  // URL -> `/dashboard?query=my-project`
  // `query` -> 'my-project'
  return <>The query: {query}</>
}

参考:https://nextjs.org/docs/app/api-reference/functions/use-search-params

相关问题