多个渲染问题,我如何在这里使用useEffect



使用此函数过滤数据,如果我在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钩子来改变路径和设置数据,这里是代码的和平。这里无论何时都有你的道具。当数据可用时,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。你不需要它们来过滤数组。

相关内容

最新更新