微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多重渲染问题以及如何在此处使用 useEffect

如何解决多重渲染问题以及如何在此处使用 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 钩子来更改路径并设置数据,这里是代码的和平之处。在这里,无论何时您的 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。您不需要它们来过滤数组。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。