首页 > 解决方案 > 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触发器,如果​​每次渲染都保存到后端服务器,则会出现性能问题。自动保存仅在组件卸载之前发生一次。用户可以点击BackHome按钮离开页面。

标签: react-nativereact-hooks

解决方案


你必须在功能组件中使用 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*/)
}

推荐阅读