React路由器如何获取当前路径并查找其更新
React router how to get current path and look for its updates
您好,我有疑问如何使用搜索参数获取应用程序的当前路径并查找其更新。例如,我有 localhost3000/?filter=breakfastdinner
,我想返回 localhost3000/?filter=breakfast
。我想等待 URL 更新以使用 useEffect。
useEffect(() => {
for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.addFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.removeFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
}
initial = false;
console.log(chosenFiltersTypes);
}, []);
如何使用 useRouter();
并在 useEffect deps 中传递路由,例如:
const { asPath } = useRouter(); // asPath or whatever from the router
useEffect(() => {
for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.addFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.removeFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
}
initial = false;
console.log(chosenFiltersTypes);
}, [asPath]);
编辑:
对于 react-router 这些挂钩如何(根据您的目标)?
useHistory
useLocation
useParams
useRouteMatch
我认为 v6 也支持所有这些。
使用 useLocation()
钩子。
const { hash, pathname, search } = useLocation();
您好,我有疑问如何使用搜索参数获取应用程序的当前路径并查找其更新。例如,我有 localhost3000/?filter=breakfastdinner
,我想返回 localhost3000/?filter=breakfast
。我想等待 URL 更新以使用 useEffect。
useEffect(() => {
for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.addFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.removeFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
}
initial = false;
console.log(chosenFiltersTypes);
}, []);
如何使用 useRouter();
并在 useEffect deps 中传递路由,例如:
const { asPath } = useRouter(); // asPath or whatever from the router
useEffect(() => {
for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.addFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
dispatch(
recipeAction.removeFilters({
content: recipeTypesArray[i],
filterName: "filterTypes",
})
);
}
}
initial = false;
console.log(chosenFiltersTypes);
}, [asPath]);
编辑:
对于 react-router 这些挂钩如何(根据您的目标)?
useHistory
useLocation
useParams
useRouteMatch
我认为 v6 也支持所有这些。
使用 useLocation()
钩子。
const { hash, pathname, search } = useLocation();