React 挂钩子组件 useEffect 在父组件之前先执行

IT技术 javascript reactjs react-hooks
2021-05-16 19:12:04

我正在学习 React 钩子 useEffect 并且我对 useEffect 的执行顺序感到困惑。在控制台中,它告诉我首先执行 ChildComponent“子组件”console.log,然后是“挂载时”useEffect,最后记录“父组件”。我希望首先记录“挂载”,然后是“父组件”,最后是“子组件”。谁能解释为什么孩子首先登录,或者为什么事情以这种方式执行?

字段是一个简单的对象数组

const fields = [
    {
        id    : 'month',
        title : 'Month'
    },
    {
        id    : 'amount',
        title : 'Amount'
    },
    {
        id    : 'year',
        title : 'Year'
    },
];

import React, { useEffect, useState } from 'react';

export default function ParentComponent(props) {
    const [fields, setFields] = useState(props.fields || []);

    useEffect(() => {
        console.log('on mount');
    }, []);

    useEffect(() => {
        console.log('parent component');
    }, [fields]);

    function randomString() {
        return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    }



    return (
        <div>
            <button
                onClick={() => setFields([...fields,...[{id: randomString(), title: randomString()}]])}
            >Change field</button>
            <ChildComponent fields={fields}/>
        </div>
    );
}

function ChildComponent(props) {
    useEffect(() => {
        console.log('child component')
    }, [props.fields]);
    return (<div>
        {props.fields.map(({ id, title }) => <div key={id} className="field">{title}</div>)}
    </div>)
}

在此处输入图片说明

1个回答

它与javascript 事件冒泡相同,这意味着当它运行时,它会调用所有ParentComponent函数,这些函数将调用和渲染ChildComponent,一旦调用了内部函数(子渲染),它将再次冒泡到顶部,现在ParentComponent's useEffect开始了在和将有序。 在此处输入图片说明

我修改了你的代码,所以你可以看到更多我指的顺序 https://codesandbox.io/s/silly-jennings-9hwwv?file=/src/App.js

在此处输入图片说明