简体   繁体   中英

react native: Warning: Can't perform a React state update on an unmounted component

I would love to understand what needs to be fixed in useEffect to fix the error described.

here is the "dataSource":

 [{"isSelect":false,
   "selectedClass":null,
   "zoneId":1026,
   "zoneName":"tomato"},
  {"isSelect":false,
   "selectedClass":null,"zoneId":1025,
   "zoneName":"apple"}]
function Button1(props) {
const [listSelectedZoneIds, setListSelectedZoneIds] = useState([]);

  useEffect(() => {
    let listSelectedZoneIds = dataSource
      .filter((zone) => zone.isSelect === true)
      .map((zone) => zone.zoneId);
    setListSelectedZoneIds(listSelectedZoneIds);
  }, [dataSource]);

  useEffect(() => {
    eventEmitter?.emit('selected', listSelectedZoneIds);
  }, [listSelectedZoneIds]);
}

Its because you have not provide the cleanup function in the useEffect function. There is something which is changing in the data sources and thus useEffect is triggered, but actually the screen is not in focused, you can solve it with the following codes, and read more about cleanup useEffect from the given link: https://dev.to/otamnitram/react-useeffect-cleanup-how-and-when-to-use-it-2hbm

useEffect(() => {
    let isMounted = true;

    if (isMounted) {
      (() => {
       let listSelectedZoneIds = dataSource
  .filter((zone) => zone.isSelect === true)
  .map((zone) => zone.zoneId);
setListSelectedZoneIds(listSelectedZoneIds);
      })();
    }

    return () => {
      isMounted = false;
    };
  }, [dataSource]);

2nd one would be:

useEffect(() => {
        let isMounted = true;

    if (isMounted) {
      (() => {
       eventEmitter?.emit('selected', listSelectedZoneIds);
      })();
    }

    return () => {
      isMounted = false;
    };
  }, [listSelectedZoneIds]);

Basically, the above codes will help you to make the useEffect only update the screen if it is mounted in the stack, and if it is not mounted the state is not gonna update till screen mount in stack. Reffer to the above link to help understand better why the error/warning is appearing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM