Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

后端 未结 5 567
小鲜肉
小鲜肉 2020-12-08 18:29

I\'m trying to add a snackBar in order to display a message whenever a user signIn or not. SnackBar.jsx:

import React from \"react\";
import PropTypes from \         


        
5条回答
  •  再見小時候
    2020-12-08 18:48

    I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

    const SingInContainer = ({ message, variant}) => {
        const [open, setSnackBarState] = useState(false);
        const handleClose = (reason) => {
            if (reason === 'clickaway') {
              return;
            }
            setSnackBarState(false)
    
          };
    
        if (variant) {
            setSnackBarState(true); // HERE BE DRAGONS
        }
        return (
            
    ) }

    Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

    const SingInContainer = ({ message, variant}) => {
        const [open, setSnackBarState] = useState(variant ? true : false); 
                                      // or useState(!!variant); 
                                      // or useState(Boolean(variant));
        const handleClose = (reason) => {
            if (reason === 'clickaway') {
              return;
            }
            setSnackBarState(false)
    
          };
    
        return (
            
    ) }

    Comprehensive Demo

    See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

提交回复
热议问题