【发布时间】:2021-09-27 12:00:01
【问题描述】:
我正在学习 react hooks useEffect,但我对 useEffect 的执行顺序感到困惑。在控制台中,它告诉我首先执行 ChildComponent“子组件”console.log,然后执行“挂载”useEffect,最后记录“父组件”。我期望首先记录“挂载”,然后是“父组件”,最后是“子组件”。 谁能解释为什么孩子先登录,或者为什么事情会这样执行?
Fields 是一个简单的对象数组
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>)
}
【问题讨论】:
-
事件冒泡的顺序几乎相同。首先自上而下进行渲染,然后自下而上进行安装/效果执行。 useEffect 不是 setTimeout,更像是事件处理。
标签: javascript reactjs react-hooks