好的,所以我有這個表單,用戶可以在其中查詢型別為“單選按鈕”搜索輸入和一個反應選擇填充類別的搜索,該按鈕用作鏈接前端表單以進行澄清
{selectedOption ?
<Link to={`/annonser${typeToRoute}${selectedOptionToRoute}${searchToRoute}`} >
<button>Hitta annons / m?nster</button>
</Link>: <Link to={`/annonser${typeToRoute}${searchToRoute}`} >
<button>Hitta annons / m?nster</button>
然后我想查詢 db 以使用 useParams 鉤子根據 url 引數獲取資料,然后設定狀態
const { type, category, search} = useParams();
const categoryRef = db.collection("articles").where("subCategory", "==", category)
我希望用戶能夠單獨搜索任何替代方案,我不會使用任何表單驗證來確保用戶的所有內容都不為空。這是正確的方法嗎?因為某種原因,您在 v6 的路由組件中不能有可選引數?有沒有其他方法可以實作我想要做的事情,或者我是否在正確的軌道上?提前感謝從未做過這樣的事情。如果我的問題問得不好,請告訴我,因為我在這里沒有很多提問的經驗。
uj5u.com熱心網友回復:
如果您想要可選的路由路徑引數,請查看此答案,要點是您為每個可以匹配的路由宣告一個路由。但是這里的問題是順序很重要,需要提供“型別”才能使“類別”成為可選,并且需要同時提供“型別”和“類別”才能使“搜索”成為可選。
這是一個示例,說明為什么這并不理想:
<Route path="/annonser/:type" element={.....} />
<Route path="/annonser/:type/:category" element={.....} />
<Route path="/annonser/:type/:category/:search" element={.....} />
在您想要“型別”和“搜索”的組合之前,這是可以的。如果您嘗試path="/annonser/:type/:search",則它具有與 相同的特異性path="/annonser/:type/:category",因此首先列出的路線就是要匹配的路線。
使用 queryString 方法,可以提供/可選且有效。
例子:
- 路線
<Route path="/annonser" element={.....} /> - 網址
"annonser?type=customType&category=foo&search=bar"
使用useSearchParams鉤子訪問 queryString 引數。
const [searchParams] = useSearchParams();
...
const type = searchParams.get("type"); // "customType"
const category = searchParams.get("category"); // "foo"
const search = searchParams.get("search"); // "bar"
const categoryRef = db.collection("articles").where("subCategory", "==", category)
任何未提供的 queryString 引數在查詢時都將回傳null。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497734.html
