我有一个 React Native 组件,它对组件中的Image.getSize
每个图像发出请求。然后在Image.getSize
请求的回调中,我为我的组件设置了一些状态。一切正常,但问题是用户可能会在一个或多个Image.getSize
请求响应之前从使用该组件的屏幕转换,这会导致“无操作内存泄漏”错误弹出,因为我'试图在组件卸载后更改状态。
所以我的问题是:如何Image.getSize
在组件卸载后阻止请求尝试修改状态?这是我的组件代码的简化版本。谢谢你。
const imgWidth = 300; // Not actually static in the component, but doesn't matter.
const SomeComponent = (props) => {
const [arr, setArr] = useState(props.someData);
const setImgDimens = (arr) => {
arr.forEach((arrItem, i) => {
if (arrItem.imgPath) {
const uri = `/path/to/${arrItem.imgPath}`;
Image.getSize(uri, (width, height) => {
setArr((currArr) => {
const newWidth = imgWidth;
const ratio = newWidth / width;
const newHeight = ratio * height;
currArr = currArr.map((arrItem, idx) => {
if (idx === i) {
arrItem.width = newWidth;
arrItem.height = newHeight;
}
return arrItem;
});
return currArr;
});
});
}
});
};
useEffect(() => {
setImgDimens(arr);
return () => {
// Do I need to do something here?!
};
}, []);
return (
<FlatList
data={arr}
keyExtractor={(arrItem) => arrItem.id.toString()}
renderItem={({ item }) => {
return (
<View>
{ item.imgPath ?
<Image
source={{ uri: `/path/to/${arrItem.imgPath}` }}
/>
:
null
}
</View>
);
}}
/>
);
};
export default SomeComponent;