React Native:如何检测功能组件将卸载?

时间:2020-07-25 00:51:30

标签: 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
      }
    }

useEffect在每次渲染时都会触发,如果每次渲染时都保存到后端服务器,则会出现性能问题。自动保存仅在组件卸载之前发生一次。用户可以单击BackHome按钮离开页面。

1 个答案:

答案 0 :(得分:2)

您必须对功能组件中的componentWillUnmount使用useEffect。

<svg *ngFor="let ncircles of total_circles|times; index as id"
    id="{{ 'eatable_' + id }}"
    [attr.width]=eatable_data.box_size
    [attr.height]=eatable_data.box_size>
      <circle cx="20" cy="20" stroke-width="1"
        [attr.r]=eatable_data.radius
        [attr.stroke]=eatable_data.stroke_color
        [attr.fill]="eatableFillColor(id)"
      />
</svg>