javascript 无法使用react-router-dom链接重置状态

iklwldmw  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(204)

我有一个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)}
/>

问题是,假设我在category1ProductSearchScreen中,点击了几个复选框,在searchBar中,我键入category2并导航到category2页面,复选框仍然保留checkedcategory2
虽然我在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>
    )
}
k3bvogb1

k3bvogb11#

Filters组件在装载时只检查一次查询参数。如果它需要对"categories"查询参数的变化做出React,那么它还应该实现一个生命周期钩子,例如useEffect,以更新selectedCategories

function Filters({ uniqueCategories }) {
  const [queryParams, setQueryParams] = useSearchParams();
  const categories = queryParams.get('categories');

  const [selectedCategories, setSelectedCategories] = useState(categories?.split(',') ?? []);

  useEffect(() => {
    setSelectedCategories(categories?.split(',') ?? []);
  }, [categories]);

  ...

  return (
    ...
  );
}

请注意,当您看到您已经编写了useState/useEffect组合时,您可能实际上只需要useMemo钩子。

function Filters({ uniqueCategories }) {
  const [queryParams, setQueryParams] = useSearchParams();
  const categories = queryParams.get('categories');

  const selectedCategories = useMemo(() => {
    return categories?.split(',') ?? [];
  }, [categories]);

  ...

  return (
    ...
  );
}

相关问题