问题
I am new to React and have a question regarding passing down functions in a state. I have a couple of 'sorting functions' in my util folder, which look like this:
export const sortColdestSummerCountries = (filteredCountries) => {
return filteredCountries.sort(
(a, b) => a.avsummertemp20802099 - b.avsummertemp20802099
);
};
and a few others:
sortHighestSummerTemp, sortLargestIncreaseHotDays, sortColdestSummerCountries, sortMostColdDays, sortWorstAffectedCountries
which pretty much look similar. I use them to sort my data by users' request, and if I wrap sortHighestSummerTemp(filteredCountries)
around my data, it works as a charm.
Now the issue: because I will have eventually 10+ filters, it makes sense to me to create a global const [queryFilter, setQueryFilter] = useState({ sortHighestSummerTemp});
which then responds to const onChangeQueryFilter = (e) => { setQueryFilter(e.target.value); };
Yet, upon trying queryFilter (filteredCountries)
the terminal shows me "queryFilter is not a function"
when I filter it? It's still the same sortHighestSummerTemp function right or what am I missing here? Do I summarize this problem correctly?
Hopefully it was clear and you understand what I am trying to do. Could anyone explain me what is going on and what's the best practice here?
UPDATE: Prateek suggested the following:
function sortBy(filteredCountries, sortKey) { return [...filteredCountries].sort((a, b) => a[sortKey] - b[sortKey]); } const [queryFilter, setQueryFilter] = useState({ sortMostHotDays, }); const filteredData = sortBy(filteredCountries, sortMostHotDays); console.log(filteredData);
This does not work, it still shows the old data (filteredCountries) but the filtering does not work. Does someone have a clue?
回答1:
1st approach
- You are putting string into your state. Maybe it's better if you use an object with sort functions and use user input as key to the sorting functions object
const onChangeQueryFilter = (e) => { setQueryFilter(e.target.value); };
const sortingFns = {
"temp": sortHighestSummerTemp,
"hot": sortLargestIncreaseHotDays,
"summer": sortColdestSummerCountries,
"cold": sortMostColdDays,
.....
}
const sortedData = sortingFns[queryFilter](data);
2nd Approach
- It is much better if you pass sorting parameter to your factory of sorting functions.
function sortBy(data, sortKey) {
return [...data].sort((a, b) => a[key] - b[key])
}
// the query filter should respond to the key on which you should sort the data.
const [queryFilter, setQueryFilter] = React.useState('');
const filteredData = sortBy(data, queryFilter);
来源:https://stackoverflow.com/questions/65933392/passing-a-function-to-state-in-react