使用<> 密码>useSearchParams hook to take the current state Value and Update the URL search params。
例:
import { useSearchParams } from react-router-dom ;
const FilterOption = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [postCode, setPostCode] = useState();
const [price, setPrice] = useState();
const [bedroomCount, setBedroomCount] = useState(
Number(searchParams.get("bedrooms") ?? 0)
);
const [bathroomCount, setBathroomCount] = useState(
Number(searchParams.get("bathrooms") ?? 0)
);
const [parkingCount, setParkingCount] = useState(
Number(searchParams.get("parking") ?? 0)
);
const searchHandler = () => {
setSearchParams(searchParams => {
searchParams.set("bedrooms", bedroomCount);
searchParams.set("bathrooms", bathroomCount);
searchParams.set("parking", parkingCount);
return searchParams;
});
};
...
}
如果你对搜索灯片需要更多控制,那么你可以检查点数,并在计数为零的地方清除碎片。
const searchHandler = () => {
setSearchParams(searchParams => {
if (bedroomCount) {
searchParams.set("bedrooms", bedroomCount);
} else {
searchParams.delete("bedrooms");
}
if (bathroomCount) {
searchParams.set("bathrooms", bathroomCount);
} else {
searchParams.delete("bathrooms");
}
if (parkingCount) {
searchParams.set("parking", parkingCount);
} else {
searchParams.delete("parking");
}
return searchParams;
});
};