【问题标题】:Error: Invalid hook call. Hooks can only be called inside of the body of a function component. (React-hooks React-native)错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。 (React-hooks React-native)
【发布时间】: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 只能在函数组件的主体内部调用。这可能是由于以下原因之一:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用中拥有多个 React 副本

我还是这个 React 钩子的新手

【问题讨论】:

    标签: react-native react-hooks


    【解决方案1】:

    import React, { useEffect } from 'react';

    在这个文件中导入 react 并为这个函数返回 null 然后它就可以工作了。 为什么会这样? -> 上面你已经创建了一个函数,并且为了将它理解为函数组件,它需要在顶部有导入并返回 null,因为你没有任何东西可以在这个函数中呈现。

    【讨论】:

    • 我已经按照你说的导入了,但是还是不行
    • 你能分享你在哪里调用这个函数吗?因为这个函数只能在组件内部调用。
    猜你喜欢
    • 2022-01-09
    • 2021-03-30
    • 2021-11-06
    • 1970-01-01
    • 2020-06-22
    • 2019-09-07
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多