反应使用使用当前道具进行效果清理 [英] React useEffect cleanup with current props
问题描述
在卸载组件但可以使用当前道具时,我遇到了需要清洁useEffect的问题.像componentWillUnmount一样,可以通过获取this.props.whatever
I ran into a need of cleaning a useEffect when component is unmounted but with an access to the current props. Like componentWillUnmount can do by getting this.props.whatever
这是一个小例子:单击设置计数"按钮5次,然后查看您的控制台.您将在B组件的console.log中看到0,无论"count"为5 https://codesandbox.io/embed/vibrant-feather-v9f6o
Here is a small example: Click "set count" button 5 times and look at your console. You'll see 0 from the console.log in component B, regardless "count" will be 5 https://codesandbox.io/embed/vibrant-feather-v9f6o
如何实现在useEffect清理功能(本例中为5)中获取当前道具的行为?
How to implement the behavior of getting current props in useEffect cleanup function (5 in my case)?
更新:将计数传递给useEffect的依赖项将无济于事,因为:
UPDATE: Passing count to the dependencies of useEffect won't help because:
- 每次将新计数传递给道具时都会调用清理
- 最后一个值为4,而不是所需的5
推荐答案
由于这个问题是从另一个问题中引用的,因此由于没有公认的答案,因此会对此做一些严重的挖掘.
Was referenced to this question from another one so will do a bit of grave digging for it since there is no accepted answer.
您想要的行为永远不会发生,因为B永远不会以计数值为5进行渲染,而当count为5时,组件A将不会渲染组件B,因为它会渲染B的卸载后的而不是呈现的最后一个值B为4.
The behaviour you want can never happen because B never renders with a count value of 5, component A will not render component B when count is 5 because it'll render unmounted instead of B, the last value B is rendered with will be 4.
如果要让B在卸载时记录它拥有的最后一个计数值,可以执行以下操作:
If you want B to log the last value it had for count when it unmounts you can do the following:
请注意,效果会在所有组件渲染完成后 执行
Note that effects executes after all components have rendered
const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
return isMounted;
};
const B = ({ count }) => {
const mounted = useIsMounted();
React.useEffect(() => {
// eslint-disable-next-line react-hooks/exhaustive-deps
return () => !mounted.current && console.log(count);
}, [count, mounted]);
return <div>{count}</div>;
};
const A = () => {
const [count, setCount] = React.useState(0);
const handleClick = React.useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []);
if (count === 5) {
//B will never be rendered with 5
return <div>Unmounted</div>;
}
return (
<React.Fragment>
<B count={count} />
<button onClick={handleClick}>Set count</button>
</React.Fragment>
);
};
ReactDOM.render(<A />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这篇关于反应使用使用当前道具进行效果清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!