我在我的react项目中使用此代码当使用USESTATE更改Data1时,我会看到Data1更改为1,但是当删除组件Data1为默认值0时。怎么了?代码是:
useEffect( () => console.log( ["mount",data1] ), [] );
useEffect( () => console.log( ["will update",data1] ) );
useEffect( () => () => console.log( ["unmount",data1] ), [] );
登录何时安装和更改为:
["mount", "0"]
["will update", "0"]
["will update", "2"]
["unmount", "0"]
当您定义效果(如
)时useEffect( () => () => console.log( ["unmount",data1] ), [] );
您本质上告诉它在初始渲染上运行,因此回调指向的Data1是其从闭合所继承的初始值,并且由于该函数不再初始化
,因此从未进行过更新,并且永远不会更新如果有任何原因,您希望在useEffect
中访问Data1,则必须将其作为第二个参数传递给useEffect
useEffect( () => () => console.log( ["unmount",data1] ), [data1] );
在这种情况下,效果将被清除任何data1
的更改
您还可以利用useRef
存储数据并在Unmount中访问数据。
function App() {
const [data1, setData1] = useState(0);
const refAttr = useRef();
useEffect(
() => () => {
console.log("unmount", refAttr.current);
},
[]
);
useEffect(() => {
setInterval(() => {
setData1(data1 => {
refAttr.current = data1 + 1;
return data1 + 1;
});
}, 1000);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
工作演示
i最终使用此功能在删除时获取最后一个数据
感谢" nima arefi"写
const useTaskBeforeUnmount = ( calback, ...data ) => {
const mounted = React.useRef( null );
React.useEffect( () => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, [] );
React.useEffect(
() => () => {
if ( !mounted.current ) {
calback( { ...data } );
}
},
[ calback, ...data ],
);
};
然后在我的组件中使用它
useTaskBeforeUnmount( console.log, data1, data2, data3 );