【问题标题】:How to check my conditions on react hooks如何检查我在反应钩子上的条件
【发布时间】:2020-09-12 16:13:29
【问题描述】:

我需要在启动或更改值时检查我的反应钩子的条件 我通过这段代码尝试过,但没有 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 中检查这种情况是一种好习惯吗?

【问题讨论】:

    标签: reactjs react-native react-hooks use-effect use-state


    【解决方案1】:

    Hi on startup useEffect with empty array 将被触发,这将在页面加载期间发生(第一次),因此您可以在那里写下您的条件。这是一个例子:

    useEffect(()=> {
    
        // Your condition here
    
    }, []);
    

    如果你有一个像value 这样的变量,那么你可以像下面这样写另一个useEffect,并将useEffect 的第二个参数中的变量(值)设置为一个数组

    const [value, setValue] = useState('');
    useEffect(()=> {
    
        // Your condition here
    
    }, [value]);
    

    【讨论】:

      【解决方案2】:
      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]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-20
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        • 2021-03-21
        相关资源
        最近更新 更多