简体   繁体   中英

React Native - Too Many Re-Renders

I am trying to create a state where it shows the visibility of some components depending on if the props are not empty. I have used an if statement as shown in the code however, it creates an error where there are too many re-renders happening. If i set a default let showComponents = false or true, everything works fine. Any idea on how to fix this issue as the visibility of the components is dependent on if the props are empty or not.

Code:

const [showcComponents, setView] = useState(false);
...
if (props.params == undefined) {
setVisibility(false);
} else {
setVisibility(true);
}

For every update in sent to your component you are calling setVisibility(false/true). This is probably messing with the rendering method in react creating a rendering loop. You should try not to call a function outside a hook. Assuming you have a visibility variable you can try:

...
useEffect(()=>{
    if(props.params === undefined && visibility === true){
         setVisibility(false);
    }else if(props.params !== undefined && visibility === false){
         setVisibility(true);
    }
}, [props.params]
)
...

This code will result in infinite re-render cycles. Because each time the component will render it will call setVisibility which will re-render the component

const [showcComponents, setView] = useState(false);
useEffect(()=>{
  if (props.params == undefined) {
    setVisibility(false);
  } else {
    setVisibility(true);
  }
}, [props.params])

Also you can write is shorter like this:

useEffect(()=>{
    setVisibility(props.params !== undefined);
}, [props.params])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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