gpt4 book ai didi

javascript - React Hook 子组件 useEffect 在父组件之前先执行

转载 作者:行者123 更新时间:2023-12-04 14:03:11 31 4
gpt4 key购买 nike

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

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>)
}

enter image description here

最佳答案

javascript event bubbling这意味着当它运行时,它会调用所有 ParentComponent函数,将调用和呈现 ChildComponent ,一旦调用了内部函数(子渲染),它将再次冒泡到顶部,现在是 ParentComponent's useEffect开始并会井然有序。
enter image description here
我对你的代码做了一些修改,所以你可以看到更多我指的顺序
https://codesandbox.io/s/silly-jennings-9hwwv?file=/src/App.js
enter image description here

关于javascript - React Hook 子组件 useEffect 在父组件之前先执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69340168/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com