How to sync props to state using React hooks : setState()

后端 未结 6 1167
深忆病人
深忆病人 2020-12-07 18:19

I am trying to set the state using React hook setState() using the props the component receive. I\'ve tried using the below code:

import React,{useState , us         


        
6条回答
  •  情深已故
    2020-12-07 18:50

    This general idea can be put into hook:

    export function useStateFromProp(initialValue) {
      const [value, setValue] = useState(initialValue);
    
      useEffect(() => setValue(initialValue), [initialValue]);
    
      return [value, setValue];
    }
    
    
    function MyComponent({ value: initialValue }) {
      const [value, setValue] = useStateFromProp(initialValue);
    
      return (...);
    }
    

提交回复
热议问题