为什么useEffect在不更改依赖项的情况下触发?

时间:2020-05-06 18:44:42

标签: react-native use-effect

仅在setCart触发useEffect时才需要。但这没有发生:

import React from 'react'
import { View } from 'react-native'

const CartScreen = () => {

    const [cart, setCart] = React.useState([])

    React.useEffect(() => {
        console.log('test');
    }, [cart])

    return (
        <View>
        </View>
    )
}

export default CartScreen;

输出:测试

即使没有碰到购物车状态也能触发

1 个答案:

答案 0 :(得分:1)

useEffect将始终在首次呈现组件时运行。如果您只想在更改状态后运行某些代码,则可以使用if语句进行检查

 private String printForegroundTask() {
        String currentApp = "NULL";
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*1000, time);
            if (appList != null && appList.size() > 0) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                for (UsageStats usageStats : appList) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (mySortedMap != null && !mySortedMap.isEmpty()) {
                    currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        } else {
            ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }
        // Log.e("AppLockerService", "Current App in foreground is: " + currentApp)
            return currentApp;
    }