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

后端 未结 6 1162
深忆病人
深忆病人 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 19:05

    For that, you need to use the useEffect so your code looks like. As you want to avoid to re-render again if pros didn't change then you have to check first on useEffect and then set the props to current variable.

    import React, { useState, useEffect } from "react";
    
    const Persons = props => {
      // console.log(props.name);
    
      const [nameState, setNameState] = useState(props);
    
      console.log(nameState.name);
      console.log(props.name);
      useEffect(
        () => {
          if (nameState !== props.name) {
            setNameState(props.name);
          }
        },
        [nameState]
      );
      return (
        

    My name is {props.name} and my age is {props.age}

    My profession is {props.profession}

    ); }; export default Persons;

    Demo

提交回复
热议问题