reactjs - 如何检查我的反应钩子条件
问题描述
我需要在启动或更改值时检查我的反应钩子的条件我通过这段代码尝试但我无法在没有 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 中检查这种情况是一种好习惯吗?
解决方案
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]);
推荐阅读
- python - pip install 使 ConnectionRefusedError: [WinError 10061]
- python - 当音频设备被拉出/断开时停止脚本pyaudio
- amazon-web-services - 从其他安全组引用 AWS 安全组
- python - 如何在不影响条形宽度的情况下调整堆叠条形图(Matplotlib)中条形之间的空间?
- c++ - 如何使用 Cmake 在 ac 项目中包含 c++ 库
- java - 如何显示从当前位置到固定位置的导航路线?
- php - PHP intval() 基本计算的奇怪结果
- matlab - 在 Matlab 中获得两个输出而不是一个
- node.js - 执行“ng new”命令时出现 NPM 错误
- apache - htaccess 从旧域中重写 URL 删除 URL 内的路径