【发布时间】:2021-10-27 06:51:26
【问题描述】:
const MyComp = someValue => (
useEffect(() => {
console.log('[1]run effect for instance with value', someValue);
return () => console.log('[2]do effect clean up for instance with value', someValue);
}, []);
return <div />;
);
const MyList = () => {
const [ showFirstInstance, setValue ] = useState(false);
return (<div>
<div onClick={ () => setValue(true) }>Click me</div>
{ showFirstInstance && <MyComp someValue='1' /> } {/* FIRST INSTANCE */ }
{ !showFirstInstance && <MyComp someValue='2' /> } {/* SECOND INSTANCE */ }
</div>);
};
render(MyList, document.getElementById('root'));
我确实根据经验测试了一段类似的代码(尽管使用上下文/调度而不是状态),并且在我使用同一组件的 N 个实例测试的有限情况下,以下问题的答案将是“是”,其中只有一个同时处于活动状态。
一般会在一般情况下首先为活动实例 (<MyComp someValue='2' />) 运行效果清理 [2],然后然后为新激活的实例(<MyComp someValue='1' />)运行初始化效果[1],无论渲染树中组件的顺序如何?
order of the components in the rendering tree 我的意思是:无论<MyComp someValue='1' /> 和<MyComp someValue='2' /> 在函数中是否交换,或者showFirstInstance 的初始值是true 或false。所以基本上,这些实例的任何渲染顺序。
【问题讨论】: