【发布时间】:2020-11-20 00:54:58
【问题描述】:
之前我尝试将下面的代码更改为 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);
}
}
这是我一直试图使其成为反应钩子的代码:
function foregroundService () {
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();
}, [])
};
我得到一个错误: 错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能是由于以下原因之一:
- 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能违反了 Hooks 规则
- 您可能在同一个应用中拥有多个 React 副本
我还是这个 React 钩子的新手
【问题讨论】: