react-native - React Native:如何检测功能组件将卸载?
问题描述
我的 RN 0.62.2 应用程序需要在功能组件卸载之前自动保存页面数据。这个想法是,当用户关闭页面时(检测失去焦点可能在这里不起作用,因为用户可以在模式屏幕中放大图像),然后自动触发保存(到后端服务器)。既然是功能组件,怎么知道组件什么时候卸载呢?
这是一个功能组件的示例代码应该做的:
const MyCom = () => {
//do something here. ex, open gallery to upload image, zoon in image in `modal screen, enter input`
if (component will unmount) {
//save the data by sending them to backend server
}
}
每次渲染的useEffect
触发器,如果每次渲染都保存到后端服务器,则会出现性能问题。自动保存仅在组件卸载之前发生一次。用户可以点击Back
或Home
按钮离开页面。
解决方案
你必须在功能组件中使用 useEffect for componentWillUnmount。
const MyCom = () => {
//do something here. ex, open gallery to upload image, zoon in image in
useEffect(() => {
// Component Did Mount
return => {
// ComponentWillUnmount
}
},[])
return(/*Component*/)
}
推荐阅读
- javascript - 如何根据 chrome 扩展中的页面显示弹出窗口?
- amazon-web-services - 修改 AWS 切换角色显示名称
- firebase - 我可以使用 firebase 创建以下后端(是否可能)?
- sql-server - SQL Server 对象资源管理器中的缺失任务选项
- python - chown: 无法访问 '/var/lib/odoo': 没有这样的文件或目录
- python - 除非我包含错误的代码行,否则 PYTHON 无法显示图像
- flutter - 如何将按下按钮的颜色更改为绿色,将行中的其他按钮颜色更改为中性
- java - ApacheBeam-Java:MS-SQL - 子查询返回超过 1 个值
- android - 在 Windows 操作系统上使用 react-native 时如何生成 android 签名密钥?
- arduino - 实现 micros() 来控制 Arduino SPI 时序