带查询参数的搜索URL

问题描述 投票:0回答:1

当我想搜索产品并点击搜索按钮时,它应该被路由到“/search?q=xxxx”页面。我正在使用 React Nextjs 13,我的文件夹结构如下

  • 应用程序 -->
    • 组件 -->
      • SearchBar.tsx
    • 搜索-->
      • 布局.tsx
      • 页面.tsx

这是我的SearchBar组件代码:

`
‘使用客户端’

import React, { useState } from 'react';

import { TbSearch } from "react-icons/tb";

import { SearchBarProps } from '../../globals/types';

import { useRouter } from 'next/navigation';

const SearchBar: React.FC<SearchBarProps> = (props) => {

const [SearchQuery, setSearchQuery] = useState("");

const router = useRouter();

const handleSearch = (event: React.FormEvent) => {

    event.preventDefault();

    const encodedSearchQuery = encodeURI(SearchQuery);

    router.push(`/search?q=${encodedSearchQuery}`)

    console.log('current query ', encodedSearchQuery);
};

return (
    <form onSubmit={handleSearch} className="relative">

        <input
            value={SearchQuery}

            onChange={(e) => setSearchQuery(e.target.value)}

            placeholder={props.searchPlaceholder}

            type="text"

            className="bg-gray-100 border-0 rounded-full px-4 py-3 pl-5 w-full focus:outline-   none"
        />


        <button type="submit">

            <TbSearch

                className="absolute right-5 top-1/2 transform -translate-y-1/2 text-xl text-    primary font-bold hover:cursor-pointer"

            />
        </button>

    </form>
);`

在我的 page.tsx 中,我使用一些模拟数据。 我的问题是,我在控制台中收到了encodedSearchQuery,但添加 ?q= 后,我无法在 url 参数中获取类似于“/search?q=abc”的查询,并且它仍然保留为“/”搜索'。 我该如何解决这个问题?

reactjs next.js url-routing router
1个回答
0
投票

要将搜索查询传递到路由器推送,您可以加入与此处所示的

createQueryString
相同的值。

在目标页面上

useSearchParams

是获取参数的理想方式。

© www.soinside.com 2019 - 2024. All rights reserved.