获取页面未找到,使用查询导航时

huangapple go评论66阅读模式
英文:

Getting page not found using navigate with query

问题

我正在尝试在ReactJS中使用带有参数的导航重定向到新页面,但是我收到了页面未找到的错误。搜索页面存在。

import { useNavigate, useSearchParams } from "react-router-dom";
import { useState } from "react";
const Navbar = () => {
    const navigate = useNavigate()
    const [searchBarParams, setSearchBarParams] = useSearchParams();
    const [search, setSearch] = useState("")
    const handleClick = () => {

        navigate("/search?search_item=" + search)
        searchBarParams.set("foo", "value")
        setSearchBarParams(searchBarParams);
    }
    return (
        <div className="navbar">
            <div className="search">
                <input type="text" onChange={(e) => setSearch(e.target.value)} name="search" placeholder="Search..." />
            </div>
            <input type="button" onClick={handleClick} value="Search" />

        </div>
    )
}

export default Navbar

搜索页面

这是我尝试重定向到的页面,我希望在此页面上获取一些查询并将其用于进行一些搜索。

import { useQuery } from '@tanstack/react-query';
import React, { useEffect } from 'react';
import { makeRequest } from '../../axios';

const Search = () => {

    const { isLoading, error, data } = useQuery(["search"], () =>
        makeRequest.get("/search?search_item=search").then((res) => {
            return res.data;
        })
    );

    return (
        <div>{"search"}</div>
    )
}

export default Search

注意:在上述代码中,你需要根据你的需求更改搜索页面的逻辑,因为它目前只是返回了一个固定的字符串"search"。

英文:

I am trying to redirect to a new page in reactjs using navigate with params

but I am getting page not found error. The search page exist

import { useNavigate, useSearchParams } from &quot;react-router-dom&quot;;
import { useState } from &quot;react&quot;;
const Navbar = () =&gt; {
    const navigate = useNavigate()
    const [searchBarParams, setSearchBarParams] = useSearchParams();
    const [search, setSearch] = useState(&quot;&quot;)
    const handleClick = () =&gt; {

        navigate(&quot;/search?search_item=&quot; + search)
        searchBarParams.set(&quot;foo&quot;, &quot;value&quot;)
        setSearchBarParams(searchBarParams);
    }
    return (
        &lt;div className=&quot;navbar&quot;&gt;
            &lt;div className=&quot;search&quot;&gt;
                &lt;input type=&quot;text&quot; onChange={(e) =&gt; setSearch(e.target.value)} name=&quot;search&quot; placeholder=&quot;Search...&quot; /&gt;
            &lt;/div&gt;
            &lt;input type=&quot;button&quot; onClick={handleClick} value=&quot;Search&quot; /&gt;

        &lt;/div&gt;
    )
}

export default Navbar

Search page

This is the page I am trying to redirect to with some query I would like to get on this page and use it to make some searches.

import { useQuery } from &#39;@tanstack/react-query&#39;;
import React, { useEffect } from &#39;react&#39;
import { makeRequest } from &#39;../../axios&#39;;

    const Search = () =&gt; {
    
    
        const { isLoading, error, data } = useQuery([&quot;search&quot;], () =&gt;
            makeRequest.get(&quot;/search?search_item=search&quot;).then((res) =&gt; {
                return res.data;
            })
        );
    
        return (
            &lt;div&gt;{&quot;search&quot;}&lt;/div&gt;
        )
    }
    
    export default Search

答案1

得分: 1

问题可能是设置和传递参数到搜索页面的方式。

修改后的代码:

import { useNavigate } from "react-router-dom";
import { useState } from "react";

const Navbar = () => {
  const navigate = useNavigate();
  const [search, setSearch] = useState("");

  const handleClick = () => {
    navigate(`/search?search_item=${search}`);
  };

  return (
    <div className="navbar">
      <div className="search">
        <input
          type="text"
          onChange={(e) => setSearch(e.target.value)}
          name="search"
          placeholder="Search..."
        />
      </div>
      <input type="button" onClick={handleClick} value="Search" />
    </div>
  );
};

export default Navbar;

我移除了使用 useSearchParamssetSearchBarParams,而是直接将搜索参数作为查询字符串传递给 navigate 函数。

关于搜索页面,你可以使用 react-router-dom 中的 useLocation 钩子来访问搜索查询参数。

搜索页面:

import { useQuery } from "@tanstack/react-query";
import { useLocation } from "react-router-dom";
import { makeRequest } from "../../axios";

const Search = () => {
  const location = useLocation();
  const searchItem = new URLSearchParams(location.search).get("search_item");

  const { isLoading, error, data } = useQuery(["search"], () =>
    makeRequest.get(`/search?search_item=${searchItem}`).then((res) => {
      return res.data;
    })
  );

  return <div>{isLoading ? "Loading..." : data}</div>;
};

export default Search;

我使用了 useLocation 来访问当前位置,然后使用 URLSearchParams 提取了 search_item 查询参数。然后,这个值被用在 useQuery 钩子中,根据搜索项来获取数据。

确保你在应用程序中设置了必要的路由配置,以正确处理 /search 路由。

英文:

The issue might be due to the way of setting and passing the parameter to search page.

Modified code:

import { useNavigate } from &quot;react-router-dom&quot;;
import { useState } from &quot;react&quot;;

const Navbar = () =&gt; {
const navigate = useNavigate();
const [search, setSearch] = useState(&quot;&quot;);

const handleClick = () =&gt; {
  navigate(`/search?search_item=${search}`);
};

return (
  &lt;div className=&quot;navbar&quot;&gt;
   &lt;div className=&quot;search&quot;&gt;
     &lt;input
       type=&quot;text&quot;
       onChange={(e) =&gt; setSearch(e.target.value)}
       name=&quot;search&quot;
       placeholder=&quot;Search...&quot;
     /&gt;
    &lt;/div&gt;
   &lt;input type=&quot;button&quot; onClick={handleClick} value=&quot;Search&quot; /&gt;
  &lt;/div&gt;
 );
};

export default Navbar;

I removed the usage of useSearchParams and setSearchBarParams and instead, I directly pass the search parameter as a query string in the navigate function.

Regarding the search page, you can access the search query parameter in the Search component using the useLocation hook from react-router-dom.

Search page

import { useQuery } from &quot;@tanstack/react-query&quot;;
import { useLocation } from &quot;react-router-dom&quot;;
import { makeRequest } from &quot;../../axios&quot;;

const Search = () =&gt; {
 const location = useLocation();
 const searchItem = new URLSearchParams(location.search).get(&quot;search_item&quot;);

 const { isLoading, error, data } = useQuery([&quot;search&quot;], () =&gt;
   makeRequest.get(`/search?search_item=${searchItem}`).then((res) =&gt; {
     return res.data;
   })
 );

 return &lt;div&gt;{isLoading ? &quot;Loading...&quot; : data}&lt;/div&gt;;
};

export default Search;

I used useLocation to access the current location and then extracted the search_item query parameter using URLSearchParams. This value is then used in the useQuery hook to fetch the data based on the search item.

Make sure you have set up the necessary routing configuration in your app to handle the /search route properly.

huangapple
  • 本文由 发表于 2023年6月12日 17:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定