gpt4 book ai didi

javascript - 如何在 React Native 中取消 Image.getSize() 请求?

转载 作者:行者123 更新时间:2023-12-03 13:32:02 26 4
gpt4 key购买 nike

我正在使用 React Native 的 Image.getSize(uri, (width, height) => {}) 方法来获取远程图像的尺寸,并将其设置为组件的状态 setState():

componentDidMount() {
Image.getSize(this.props.uri, (width, height) => {
this.setState({ width, height })
})
}

但是,有时组件会在 getSize() 请求返回之前卸载,这会在调用 setState() 时导致以下错误:

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

我知道可以跟踪组件的安装状态以防止 setState() 调用,但显然this is considered an antipattern.

鉴于 getSize() 没有提供取消待处理请求的方法,是否还有其他方法可以实现此目的?

最佳答案

我也遇到了同样的问题。对我有用的是将 Image.getSize 包装在一个 promise 中:

export type CancelPromise = ((reason?: Error) => void) | undefined;
export type ImageSize = { width: number; height: number };
interface ImageSizeOperation {
start: () => Promise<ImageSize>;
cancel: CancelPromise;
}

const getImageSize = (uri: string): ImageSizeOperation => {
let cancel: CancelPromise;
const start = (): Promise<ImageSize> =>
new Promise<{ width: number; height: number }>((resolve, reject) => {
cancel = reject;
Image.getSize(
uri,
(width, height) => {
cancel = undefined;
resolve({ width, height });
},
error => {
reject(error);
}
);
});

return { start, cancel };
};

然后你可以在你的组件中使用它,如下所示:

const A: React.FC = () => {
const [size, setSize] = useState<{width: number, height: number} | undefined>(});
useEffect(() => {
let cancel: CancelPromise;
const sideEffect = async (): Promise<void> => {
try {
const operation = getImageSize(uri);
cancel = operation.cancel;
const imageSize = await operation.start();
setSize(imageSize);
} catch(error) {
if (__DEV__) console.warn(error);
}
}
sideEffect();
return () => {
if (cancel) {
cancel();
}
}
});
}

关于javascript - 如何在 React Native 中取消 Image.getSize() 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59817024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com