Fix `Image.getSize` in `useEffect` cleanup

This commit is contained in:
Zhiyuan Zheng 2020-12-26 10:39:01 +01:00
parent f990ff0cb1
commit f192939671
No known key found for this signature in database
GPG Key ID: 078A93AB607D85E0
3 changed files with 65 additions and 33 deletions

View File

@ -20,30 +20,41 @@ const AttachmentImage: React.FC<Props> = ({
}) => {
layoutAnimation()
let isMounted = false
useEffect(() => {
isMounted = true
return () => {
isMounted = false
}
})
const [imageVisible, setImageVisible] = useState<string>()
const [imageLoadingFailed, setImageLoadingFailed] = useState(false)
useEffect(
() =>
useEffect(() => {
const preFetch = () =>
isMounted &&
Image.getSize(
image.preview_url,
() => setImageVisible(image.preview_url),
() => isMounted && setImageVisible(image.preview_url),
() => {
isMounted &&
Image.getSize(
image.url,
() => setImageVisible(image.url),
() => isMounted && setImageVisible(image.url),
() =>
image.remote_url
? Image.getSize(
? isMounted &&
Image.getSize(
image.remote_url,
() => setImageVisible(image.remote_url),
() => setImageLoadingFailed(true)
() => isMounted && setImageVisible(image.remote_url),
() => isMounted && setImageLoadingFailed(true)
)
: setImageLoadingFailed(true)
: isMounted && setImageLoadingFailed(true)
)
}
),
[]
)
preFetch()
}, [isMounted])
const children = useCallback(() => {
if (imageVisible && !sensitiveShown) {

View File

@ -13,11 +13,22 @@ export interface Props {
const TimelineCard: React.FC<Props> = ({ card }) => {
const { theme } = useTheme()
let isMounted = false
useEffect(() => {
isMounted = true
return () => {
isMounted = false
}
})
const [imageLoaded, setImageLoaded] = useState(false)
useEffect(
() => card.image && Image.getSize(card.image, () => setImageLoaded(true)),
[]
)
useEffect(() => {
const preFetch = () =>
card.image &&
isMounted &&
Image.getSize(card.image, () => isMounted && setImageLoaded(true))
preFetch()
}, [isMounted])
const cardVisual = useMemo(() => {
if (imageLoaded) {
return <Image source={{ uri: card.image }} style={styles.image} />

View File

@ -17,11 +17,20 @@ const AccountHeader: React.FC<Props> = ({
}) => {
const [ratio, setRatio] = useState(accountState.headerRatio)
let isMounted = false
useEffect(() => {
isMounted = true
return () => {
isMounted = false
}
})
useEffect(() => {
if (
account?.header &&
!account.header.includes('/headers/original/missing.png')
) {
isMounted &&
Image.getSize(account.header, (width, height) => {
if (!limitHeight) {
accountDispatch &&
@ -30,10 +39,11 @@ const AccountHeader: React.FC<Props> = ({
payload: height / width
})
}
isMounted &&
setRatio(limitHeight ? accountState.headerRatio : height / width)
})
}
}, [account])
}, [account, isMounted])
const windowWidth = Dimensions.get('window').width