[英]React Router, Function not getting props
This logic is about filtering houses based on filters (such as purpose, price etc) when I change the filters nothing happens (no url change) or no error on console.此逻辑是关于基于过滤器(例如用途、价格等)过滤房屋,当我更改过滤器时没有任何反应(没有 url 更改)或控制台上没有错误。 It looks like data is not being passed to searchProperties.
看起来数据没有传递给 searchProperties。
I am unable to find any solution.我找不到任何解决方案。
Note: Ignore comments.注意:忽略评论。
import classes from "./FilterProperties.module.css";
import { useState } from "react";
import { filterData, getFilterValues } from "../../lib/filterData";
import {
useLocation,useSearchParams, useNavigate} from "react-router-dom";
import DropDown from "./DropDown";
const FilterProperties = () => {
const location = useLocation();
const [filters, setFilters] = useState(filterData);
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const searchProperties = (filterValues) => {
const path = location.pathname;
console.log(path);
const query = searchParams.get("query");
console.log(query); // undefined
const values = getFilterValues(filterValues); // error
// console.log(values);
values.forEach((item) => {
setSearchParams[item.name] = item.value;
});
navigate({ pathname: path, query });
};
return (
<div className={classes.item}>
{filters.map((filter) => (
<DropDown
key={filter.queryName}
placeholder={filter.placeholder}
filter={filter}
onChange={(e) => {
searchProperties({ [filter.queryName]: e.target.value });
}}
/>
))}
</div>
);
};
export default FilterProperties;
It seems you are misusing the setSearchParams
function.您似乎在滥用
setSearchParams
function。 The useSearchParams
hook returns a URLSearchParams
object and a setSearchParams
function that works similarly to the navigate
function but only updates the search part of the URL. The
useSearchParams
hook returns a URLSearchParams
object and a setSearchParams
function that works similarly to the navigate
function but only updates the search part of the URL. The basic gist is that you only need to iterate over the filter key-value pairs, update the searchParams
object, and then issue the imperative navigation with the updated query parameters.基本要点是您只需要遍历过滤器键值对,更新
searchParams
object,然后使用更新的查询参数发出命令式导航。
Example:例子:
...
const [searchParams, setSearchParams] = useSearchParams();
...
const searchProperties = (filterValues) => {
const values = getFilterValues(filterValues); // *
values.forEach(({ name, value }) => {
searchParams.set(name, value); // <-- set query parameter value
});
setSearchParams(searchParams); // <-- update query params
};
* Note: I am assuming that getFilterValues(filterValues)
functions and returns all the filter key-value pairs the UI is working with. *注意:我假设
getFilterValues(filterValues)
函数并返回 UI 正在使用的所有过滤器键值对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.