首页 > 解决方案 > 如何检查我的反应钩子条件

问题描述

我需要在启动或更改值时检查我的反应钩子的条件我通过这段代码尝试但我无法在没有 Btn 的情况下运行

import React,{useEffect} from 'react';
import { StyleSheet, View } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Notifications} from 'expo';
export default function NotificationsTest() {
  const y = 5;
  const askPermissionsAsync = async () => {
    await Permissions.askAsync(Permissions.USER_FACING_NOTIFICATIONS);
  };
  const btnSendNotClicked = async () => {
    if(y===5){
      await askPermissionsAsync();
      Notifications.presentLocalNotificationAsync({
        title: "Title",
        body: "****** SUBJ *******",
        ios:{
          sound:true,
        },
        android:{
          sound:true,
          color:'#512da8',
          vibrate:true,
        }
     });
    }else{ 
    }    }
  useEffect(()=>{
    return btnSendNotClicked  
  }
  ,[])
   return (
      <View style={styles.container}>
      </View>
  );  
}

我只是想确认在 useEffect 中检查这种情况是一种好习惯吗?

标签: reactjsreact-nativereact-hooksuse-effectuse-state

解决方案


const y = 5;

//this one will run every time the component renders
//so you could use it to check for anything on the startup
useEffect(()=> {

    // Your condition here

}, []);

否则,您可以添加要跟踪更改的值或值数组,这样下面的 useEffect 将仅在 y const 更改时运行,因此您可以在此处添加 if 检查以检查 y===5 是否也将运行此 useEffect在 const y 的第一个首字母上,所以在你的情况下它是完美的

}

useEffect(()=> {

    // will run every time y const change and on the first initial of y
    if (y === 5)
    {
      //do your stuff here
    }

}, [y]);

推荐阅读