【问题标题】:How to use hooks in Headless JS function with react-native-firebase?如何在带有 react-native-firebase 的 Headless JS 函数中使用钩子?
【发布时间】:2020-01-02 14:43:33
【问题描述】:

当我在后台收到通知时,我尝试使用 apollo-hooks 和 react-native-firebase 从服务器获取数据。

然后我创建了新函数和 registerHeadlessTask。

但它发生在Hooks can only be called inside the body of a function component.

反应原生:0.59.8 反应原生火力:5.5.6 反应阿波罗挂钩:0.4.5

我尝试使用 react-apollo-hooks 获取数据,但出现错误。 而且,我得到另一个上下文的自定义钩子,它也发生Hooks can only be called inside the body of a function component. 错误。

index.js:


...
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessage)

bgMessage.js:

export const bgMessage = message => {
  const [mValue, setMValue] = useTest()
  const {
    data: { type },
  } = message

  switch (type) {
    case 'Installing': {
      setMValue(type)
      displayedNotification(message, FCM_MESSAGES_STATUS.Message)
      return Promise.resolve(message)
    }
    default:
      displayedNotification(message, FCM_MESSAGES_STATUS.Message)
      return Promise.resolve(message)
  }
}

export const useTest = () => {
  const [mValue, setMValue] = useState(null)
  return [mValue, setMValue]
}

有没有办法在这里使用钩子?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    Headless JS 中不允许使用 hooks。根据issue 的答案,钩子被视为 UI 元素,因此不允许在 Headless JS 中使用。

    【讨论】:

      【解决方案2】:

      你可以试试这个。

      bgMessage.js

      import React, { useState } from 'react';
      ...
      export default async (message) => {
        const [mValue, setMValue] = useState('')
        const {
          data: { type },
        } = message
      
        switch (type) {
          case 'Installing': {
            setMValue(type)
            displayedNotification(message, FCM_MESSAGES_STATUS.Message)
            return Promise.resolve(message)
          }
          default:
            displayedNotification(message, FCM_MESSAGES_STATUS.Message)
            return Promise.resolve(message)
        }
      }
      

      【讨论】:

      • 谢谢。但是,它也会发生Hooks can only be called inside the body of a function component 错误。
      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2020-11-15
      • 2019-10-06
      • 1970-01-01
      相关资源
      最近更新 更多