我在 React 中遇到了導航邏輯的問題,如果能得到一些幫助真是太棒了。
我有用 TypeScript、React 和 Ionic Framework V5 撰寫的前端 Web 應用程式。
該應用程式有一個相當標準的搜索框,可以重定向到帶有 location 的結果頁面/search?query={query here}。
當我點擊搜索按鈕時,導航由 React Router 處理。我被重定向到結果頁面并且搜索查詢出現在瀏覽器的地址欄中,但是在功能組件邏輯中獲取查詢字串時它是空的 - 給我不正確的搜索結果。
搜索框路由到結果頁面,如下所示:
<IonButton fill="clear" className="search-button" routerLink={`/search?query=${searchValue}`}>
<IonIcon name="search-outline" />
</IonButton>
- 請注意,該
routerLink屬性只是 React Router 的 Ionic 助手,如果我將按鈕封裝在普通<Link/>標簽中,問題也是一樣的。
在搜索頁面上,查詢字串的讀取方式如下:
const Home: React.FC<SimplePageProps> = ({ axios }) => {
const queryParams = useQuery();
const param = queryParams.get('query');
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get(`/products?query=${param}`)
.then((response) => {
const data = camelcaseKeys(response.data, { deep: true });
setProducts(data.items.map((product: Product) => (
<IonCol key={product.id} size-md="4" size-xl="3">
<ProductCard product={product} />
</IonCol>
)));
})
.catch((error) => {
// TODO show error element
console.error(error);
});
}, [axios, param]);
如前所述,在功能組件邏輯中獲取查詢字串時為空 - 給我不正確的搜索結果。重繪 頁面時,查詢字串不為空,出現搜索結果。有任何想法嗎?
提前非常感謝!
uj5u.com熱心網友回復:
在睡了它并進行了更多搜索之后,我設法解決了這個問題。
我的解決方案是將事情剝離回一個普通的 JavaScript 命令,window.location.search. 這總是從 URL 中獲取正確的查詢引數,而 React Router 幫助程式掛鉤將undefined在第一次路由到頁面時。
useLocation()包含在內,這樣當從結果頁面執行另一個搜索時,React 組件會重新呈現以反映新的查詢字串。
const Home: React.FC<SimplePageProps> = ({ axios }) => {
// parse query string parameter
const { search } = window.location;
const query = new URLSearchParams(search).get('query');
useLocation(); // including this forces a re-render when the URL changes
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get(`/products?query=${query}`)
.then((response) => {
const data = camelcaseKeys(response.data, { deep: true });
setProducts(data.items.map((product: Product) => (
<IonCol key={product.id} size-md="4" size-xl="3">
<ProductCard product={product} />
</IonCol>
)));
})
.catch((error) => {
// TODO show error element
console.error(error);
});
}, [axios, query]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487825.html
