use*_*363 2 react-native react-hooks
我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
每次渲染都会触发useEffect,如果每次渲染都保存到后端服务器,则会出现性能问题。自动保存仅在组件卸载之前发生一次。用户可以单击Back或Home按钮离开页面。
小智 7
yo\xc4\xb1 必须在功能组件中使用 useEffect 来进行 componentWillUnmount。
\nconst MyCom = () => {\n\n //do something here. ex, open gallery to upload image, zoon in image in \n\n useEffect(() => {\n // Component Did Mount\n\n return () => {\n // ComponentWillUnmount\n }\n },[])\n\n return(/*Component*/)\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1713 次 |
| 最近记录: |