简体   繁体   English

React useEffect 不会根据 props 更新 state

[英]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.我是 React 的新手,正在尝试将文本编辑器添加到具有可见性等道具的弹出组件中。 Idea is to make it a component that change its visibility by prop value.想法是让它成为一个组件,通过 prop 值改变它的可见性。 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?我尝试使用 useEffect 从道具更改 state,但是,可见性不会更新 state。知道为什么这不起作用吗?

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.据我了解,您正在使用道具,然后 map 尝试使用 useState 和 useEffect 将其值映射到 state,然后使用该 state 来控制弹出窗口的可见性。 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.在这种情况下你不需要 useState,你可以直接使用 prop。 You will need to provide a function to handle the onClose.您将需要提供一个 function 来处理 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>      
  )    
}

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

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