我有一个SearchBar
组件,我有这个Link
,点击它会把我带到一个ProductSearchScreen
,它显示一组与一个类别相关联的产品。
return (
<Link to={{ pathname:# somepath, search: `searchItem=${category.name}` }}>
{category.name}
</Link>
)
在我的ProductSearchScreen
中,我有一些复选框可以过滤掉数据,比如“类别”,“品牌”过滤器等。
例如,为了筛选出类别,我有以下代码
const [selectedCategories, setSelectedCategories] = useState(queryParams.get('categories')?.split(',') ?? []);
<input
type="checkbox"
checked={selectedCategories.includes(category)}
onClick={() => handleCategories(category)}
/>
问题是,假设我在category1
的ProductSearchScreen
中,点击了几个复选框,在searchBar中,我键入category2
并导航到category2
页面,复选框仍然保留checked
为category2
。
虽然我在navigate上的queryParams
中没有任何东西,但它并没有重置selectedCategories
的状态。如何确保在导航到另一个页面时未选中复选框?
编辑:这是使用路径和查询字符串的组件
function ProductSearchScreen() {
const [products, setProducts] = useState([]);
const [queryParams] = useSearchParams();
// Here is the queryString i am getting
const category = queryParams.get('searchItem');
const categories = queryParams.get('categories')?.split(',');
const uniqueCategories = getUniqueCategories(products)
// with axios call, i get the list of products and update the state like setProducts(products).
// This is a helper function to filter the categories
const filterCategories = (product) => {
if(categories?.length > 0) {
return categories?.includes(product.category);
} else {
return product
}
}
const filteredAndSortedProducts = products?.filter(filterCategories)
return ( <Filters uniqueCategories={uniqueCategories}/> )
}
function Filters({ uniqueCategories }) {
const [queryParams, setQueryParams] = useSearchParams();
const [selectedCategories, setSelectedCategories] = useState(queryParams.get('categories')?.split(',') ?? []);
const handleCategories = (category) => {
if (selectedCategories.includes(category)) {
setSelectedCategories(selectedCategories.filter((c) => c !== category));
} else {
setSelectedCategories([...selectedCategories, category]);
}
}
return (
<div key={index} className="filter-type">
<input
type="checkbox"
disabled={queryParams.get('categories')?.split(',').includes(category)}
checked={selectedCategories.includes(category)}
onChange={() => handleCategories(category)}
/>
<div className="filter-item">{category}</div>
</div>
)
}
1条答案
按热度按时间k3bvogb11#
Filters
组件在装载时只检查一次查询参数。如果它需要对"categories"
查询参数的变化做出React,那么它还应该实现一个生命周期钩子,例如useEffect
,以更新selectedCategories
。请注意,当您看到您已经编写了
useState
/useEffect
组合时,您可能实际上只需要useMemo
钩子。