React

1. Initialize the props of each subcomponent in the following way:

// 
1. const [title2, setstate] = useState(props.title)

2. const { title } = props 

Copy the code

If you change the title value in the parent component, will the child component’s value be updated synchronously?

Const {title} = props is updated synchronously and here is a reference to the value

Const [title2, setstate] = useState(props. Title) there is no synchronization because useState gets a new value every time

The full code is as follows:

/ / the parent component
import Data from '.. /components/data'

export default function index() {
   const [title, setTitle] = useState('test')


    setTimeout(() = > {
      setTitle(Test '1')},2000)
  return (
    <div>The parent component<Data title={title}></Data>
    </div>)}Copy the code
/ / child component
export default function data(props) {

    const [title2, setstate] = useState(props.title)

    const { title } = props
     
    useEffect(() = > {
        
        console.log(title + 'title')
       
    }, [title])

    useEffect(() = > {
        console.log(title2 + 'state')  
    }, [title2])
    
    return (
        <div>
            {title}--- title <br />{title2} -- title2 {/* Not title2 */}</div>)}Copy the code