[英]Set state based on url params react-router v6
好的,所以我有這個表單,用戶可以在其中查詢類型為“單選按鈕”搜索輸入和一個反應選擇填充類別的搜索,該按鈕用作鏈接前端表單以進行澄清
{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 的路由組件中不能有可選參數? 有沒有其他方法可以實現我想要做的事情,或者我是否在正確的軌道上? 提前感謝從未做過這樣的事情。 如果我的問題問得不好,請告訴我,因為我在這里沒有很多提問的經驗。
如果您想要可選的路由路徑參數,請查看此答案,要點是您為每個可以匹配的路由聲明一個路由。 但是這里的問題是順序很重要,需要提供“類型”才能使“類別”成為可選,並且需要同時提供“類型”和“類別”才能使“搜索”成為可選。
這是一個示例,說明為什么這並不理想:
<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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.