简体   繁体   中英

React Native, add two return statements to useEffect hook

How can I add two return statements to my useEffect hook? I would like to add an event listener to my current hook.

Event listener:

const subscription = AppState.addEventListener("change", nextAppState => {
  if (
    appState.current.match(/inactive|background/) &&
    nextAppState === "active"
  ) {
    console.log("App has come to the foreground!");
  }

  appState.current = nextAppState;
  setAppStateVisible(appState.current);
  console.log("AppState", appState.current);
});

return () => {
  subscription.remove();
};

Current hook:

useEffect(() => {

    async function checkRefresh() {
        if (
            daysDiffToNow(lastUpdatedTimestamp) > 0 &&
            appState.current.match(/inactive|background/) &&
            nextAppState === "active"
        ) {
            await onRefreshAppData();
        }
    }
    checkRefresh();

    const updateLastUpdatedTextCallback = (value) => {
        setState((prevState) => ({
            ...
        }));
    };
    const id = setInterval(() => {
        updateLastUpdatedTextCallback(lastUpdatedTimestamp);
    }, TIME_INTERVAL_IN_MILISECONDS);
    return () => clearInterval(id);
}, [lastUpdatedTimestamp]);

const close = () => {
    setState((prevState) => ({
        ...
    }));
};

You could simply put them top to bottom inside the useEffect and have a return function that would look like this (it executes at once the code for the two return statements needed):

return () => {
  subscription.remove(); // the first
  clearInterval(id); // the second
};

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