How to change props to state in React Hooks?

前端 未结 4 1656
温柔的废话
温柔的废话 2021-02-02 07:41

In Simple react class component we used to change the props to state this way:

constructor(props) {
    super(props)

    this.state = {
      pitch: props.book         


        
4条回答
  •  伪装坚强ぢ
    2021-02-02 08:20

    The problem in your code is with {}. UseEffect hook expects and array, not an object. Use [initialDesc] instead.

    This is how you reset component state when props change

    const GenerateDescHook = ({ description: initialDesc }) => {
      const [description, setDescription] = useState(null)
    
      useEffect(() => {
        setDescription(initialDesc)
      }, [initialDesc]);
    }
    

    This is how you initialize component state to prop value on first render only

    const GenerateDescHook = ({ description: initialDesc }) => {
      const [description, setDescription] = useState(initialDesc);
    }
    

提交回复
热议问题