仅安装一次组件,不再次卸载它

问题描述 投票:0回答:1

也许我认为可以解决我的问题的方法不正确。很高兴听到想法。我得到:

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 async task in a useEffect cleanup function

并将其跟踪到状态栏的headerRight部分中的一个组件。我觉得它只能安装一次。无论如何,组件都会与发生的同步过程进行对话并更新状态。对于每种状态,都会显示一个不同的图标。

dataOperations是一个NativeModules类,它与进行后台同步并将状态发送到RN的某些JAVA进行通信。

import React, {useState, useEffect} from 'react';
import {DeviceEventEmitter } from 'react-native';

import DataOperations from "../../../../lib/databaseOperations"

const CommStatus: () => React$Node = () => {
  let [status, updateStatus] = useState('');
  const db = new DataOperations();

  const onCommStatus = (event) => {
    status = event['status'];
    updateStatus(status);
  };

  const startSyncing = () => {
    db.startSyncing();
  };


const listner = DeviceEventEmitter.addListener(
  'syncStatusChanged',
  onCommStatus,
);

 //NOT SURE THIS AS AN EFFECT
  const removeListner = () =>{
    DeviceEventEmitter.removeListener(listner)
  }

  //REMOVING THIS useEffect hides the error
  useEffect(() => {
    startSyncing();
    return ()=>removeListner(); // just added this to try
  }, []);



  //TODO: find icons for stopped and idle. And perhaps animate BUSY?
  const renderIcon = (status) => {
    //STOPPED and IDLE are same here.
    if (status == 'BUSY') {
      return (
        <Icon          
          name="trending-down"
        />
      );
    } else if (status == 'IS_CONNECTING') {
      ...another icon
    }
  };

  renderIcon();

  return <>{renderIcon(status)}</>;
};


export default CommStatus;

该组件作为堆栈导航的一部分加载,如下所示:

  headerRight: () => (
    <>
    <CommStatus/>
    </>
  ),
react-native
1个回答
0
投票

您可以为此使用App.js。

    <Provider store={store}>

      <ParentView>
        <View style={{ flex: 1 }}>
          <AppNavigator />
          <AppToast />
        </View>
      </ParentView>

    </Provider>

因此在这种情况下将仅安装一次。

© www.soinside.com 2019 - 2024. All rights reserved.