我需要检查我的条件反应挂钩时,启动或更改的值我尝试了这段代码,但我不能运行没有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中检查这种情况是不是一种好的做法?
发布于 2020-05-26 07:52:40
在启动时,带有空数组的useEffect将被触发,这将在页面加载期间发生(第一次),因此您可以在那里编写条件。下面是一个示例:
useEffect(()=> {
// Your condition here
}, []);如果您有一个像value这样的变量,那么您可以像下面这样编写另一个值,并在useEffect的第二个参数中将该变量( useEffect )设置为一个数组
const [value, setValue] = useState('');
useEffect(()=> {
// Your condition here
}, [value]);发布于 2020-05-26 21:40:17
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常量发生更改时运行,因此您可以添加一个if检查,以检查y===5是否也会在常量y的第一个字母上运行,因此在您的情况下它是完美的
}
useEffect(()=> {
// will run every time y const change and on the first initial of y
if (y === 5)
{
//do your stuff here
}
}, [y]);https://stackoverflow.com/questions/62012314
复制相似问题