问题描述
使用此函数过滤数据,如果我在 useEffect 中调用此函数而不是它推送到搜索结果并且无法正常工作。
const AdvanceSearch = (props) => {
const [region,setRegion] = useState("");
const [searchStuhl,setSearchStuhl] = useState("");
const filterData = (async ()=> {
const filtereddata = await props.data.filter((item) => {
return (
item.region.toLowerCase().includes(region.toLowerCase())
&& item.stuhl.toLowerCase().includes(searchStuhl.toLowerCase())
)}
) await props.history.push({
pathname: '/searchResults/',state:
{
data:filtereddata
}
})
})
//If the props. history.push is pass here instead of the above function then its sending the empty array and not the filtered data
const handleSubmit = async (e) => {
e.preventDefault()
await filterData();
}
解决方法
当您使用一些数据更改导航 URL 并且存在多次渲染时,就会出现以下问题。
- 检查路径的路由配置。是否配置为保存更改的路径:在这种情况下,您会看到 UI 波动,或者我们可以说多次渲染
- 是的,您可以使用 useEffect 钩子来更改路径并设置数据,这里是代码的和平之处。在这里,无论何时您的 props.data 将被更改,filteredData 将运行,并在数据可用时返回该值。
const filteredData = useCallback(() => {
if(props.data){
const filteredData = props.data.filter((item) => (
item.region.toLowerCase().includes(region.toLowerCase())
&&item.stuhl.toLowerCase().includes(searchStuhl.toLowerCase())
));
return filteredData
}
},[props && props.data]);
useEffect(()=> {
const data = filteredData();
if(data){
props.history.push({
pathname:'/search-results',state:{data}
});
}
},[filteredData])
尝试从函数中删除 async / await。您不需要它们来过滤数组。