简体   繁体   English

多重渲染问题以及如何在这里使用 useEffect

[英]Multiple rendering problem and how can I use the useEffect here

Filtering data by using this function, if I am calling this function in useEffect than its pushes to search results and not working well.使用此 function 过滤数据,如果我在 useEffect 中调用此 function 而不是推送到搜索结果并且效果不佳。

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();      
     
    }

when you are changing the navigation URL with some data and there is multiple rendering then the following problem would be there.当您使用一些数据更改导航 URL 并且有多个渲染时,就会出现以下问题。

  • Check your route configuration for the path.检查路径的路由配置。 is it configured to hold the changed path: in this scenario, you get fluctuated UI or we can say multiple renders它是否配置为保存更改的路径:在这种情况下,您会得到波动的 UI,或者我们可以说多个渲染
  • yes you can use useEffect hooks to change the path and set the data here is the peace of code.是的,您可以使用 useEffect 挂钩来更改路径并在此处设置数据是代码的和平。 here whenever your props.data will be changed filteredData will run and it will return the value when data will be available.每当您的 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])

Try to remove async / await from the function.尝试从 function 中删除 async / await。 You don't need them to filter an array.您不需要它们来过滤数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM