简体   繁体   中英

React useEffect does not update state based on props

I am new to React and am trying to add a text editor to a pop up component with a props like visibility. Idea is to make it a component that change its visibility by prop value. I tried to use useEffect to change the state from props, however, visibility does not update the state. Any idea why this is not working?

export default function My_editor_popup({visibility_in}) {
const [visibility, setVisibility] = useState(visibility_in);        
const popupCloseHandler = () => { setVisibility(false); };
useEffect(() => {
    setVisibility(visibility_in);        
  }, [visibility_in]);
return (  
    <div>            
        <MyPopup onClose={popupCloseHandler} show={visibility} title="Editor">            
            <My_editor text={""}/> 
        </MyPopup>
    </div>      
)    
}

As I understand, you are using a props, then map try mapping it value to a state using useState and useEffect, then use that state to control the popup visibility. I think you are complicating the problems, because you could simply use the prop to control the visibiliy as shown below

//set visibility is a function which could change value of visibility of parent component
    export default function My_editor_popup({visibility, setVisibility}) {

const popupCloseHandler = () => { setVisibility(false); };
 
return (  
    <div>            
        <MyPopup onClose={popupCloseHandler} show={visibility} title="Editor">            
            <My_editor text={""}/> 
        </MyPopup>
    </div>      
)    
}

You don't need a useState in this case, you can just use the prop directly. You will need to provide a function to handle the onClose.

export default function My_editor_popup( { visibility_in, closeHandler} ) {

return (  
    <div>            
        <MyPopup
          onClose={closeHandler}
          show={visibility_in} 
          title="Editor">            
            <My_editor text={""}/> 
        </MyPopup>
    </div>      
  )    
}

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