我试着用React Hooks让异步等待if条件。下面的代码是在我试图让它成为React Hooks之前的代码:
async startService() {
if (Platform.OS !== 'android') {
console.log('Only Android platform is supported');
return;
}
if (Platform.Version >= 26) {
const channelConfig = {
id: 'ForegroundServiceChannel',
name: 'Notification Channel',
description: 'Notification Channel for Foreground Service',
enableVibration: true,
importance: 2
};
await VIForegroundService.createNotificationChannel(channelConfig);
}
}我试着把它放进React Hooks
useEffect(() => {
async function startService() {
if (Platform.OS !== 'android') {
console.log('Only Android platform is supported');
return;
}
if (Platform.Version >= 26) {
const channelConfig = {
id: 'ForegroundServiceChannel',
name: 'Notification Channel',
description: 'Notification Channel for Foreground Service',
enableVibration: false,
importance: 2
};
await VIForegroundService.createNotificationChannel(channelConfig);
}
const notificationConfig = {
id: 3456,
title: 'Foreground Service',
text: 'Foreground service is running',
icon: 'ic_notification',
priority: 0
};
if (Platform.Version >= 26) {
notificationConfig.channelId = 'ForegroundServiceChannel';
}
await VIForegroundService.startService(notificationConfig);
}startService();
}, []);我还试图在我的jsx中调用它,如下所示:
<Button onPress={() => this.startService()}>
<Text>Tes</Text>
</Button>它没有工作,我写错了吗?
发布于 2020-07-30 13:06:16
根据您的代码,函数startService()的作用域在useEffect内的箭头函数内。它只能从useEffect中的箭头函数中访问。你要做的就是在一个没有作用域的块中调用一个函数。
第二件事,useEffect不是显式调用的东西。效果将基于依赖数组启动。Ryan Florance很好地解释了如何在这个video中使用useEffect钩子。
要使您的代码工作,您根本不需要useEffect。只需将startService()的函数定义移出useEffect,移到main函数内部或函数外部的某个地方(如果它没有任何其他依赖项)。
如果您的目标是只启动一次startService(),则可以按如下方式使用useEffect:
useEffect(() => {
startService();
},[]);另外,Button组件的用法是不正确的。如下所示:
<Button title="Tes" onPress={startService} />https://stackoverflow.com/questions/63165735
复制相似问题