React 运行 effect 在渲染新的组件实例之前是否会清理已经渲染的组件实例?
Does React run effect clean up for already rendered component instances before rendering new component instances?
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'));
我确实根据经验测试了类似的代码块(尽管使用 context/dispatch 而不是状态),并且在我用 N 个实例测试的有限情况下,以下问题的答案将是 'yes'同一组件,同时只有一个组件处于活动状态。
通常 React 16.8+ 首先 运行 效果会清除 [2] 活动实例(<MyComp someValue='2' />
) 和 then 运行 初始化效果 [1] 对于新激活的实例 (<MyComp someValue='1' />
),无论组件中的顺序如何渲染树?
By order of the components in the rendering tree
我的意思是:无论 <MyComp someValue='1' />
和 <MyComp someValue='2' />
在函数中是否交换,或者 showFirstInstance
的初始值是 真或假。所以基本上,这些实例的任何渲染顺序。
是的,React 首先运行 清除组件的效果。原因很简单,这个过程和代码中which wirst first无关,跟之前渲染过哪个component有关,所以pre state需要先清理,然后new state开始渲染。
中也有说明
When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
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'));
我确实根据经验测试了类似的代码块(尽管使用 context/dispatch 而不是状态),并且在我用 N 个实例测试的有限情况下,以下问题的答案将是 'yes'同一组件,同时只有一个组件处于活动状态。
通常 React 16.8+ 首先 运行 效果会清除 [2] 活动实例(<MyComp someValue='2' />
) 和 then 运行 初始化效果 [1] 对于新激活的实例 (<MyComp someValue='1' />
),无论组件中的顺序如何渲染树?
By order of the components in the rendering tree
我的意思是:无论 <MyComp someValue='1' />
和 <MyComp someValue='2' />
在函数中是否交换,或者 showFirstInstance
的初始值是 真或假。所以基本上,这些实例的任何渲染顺序。
是的,React 首先运行 清除组件的效果。原因很简单,这个过程和代码中which wirst first无关,跟之前渲染过哪个component有关,所以pre state需要先清理,然后new state开始渲染。
中也有说明When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.