React Native:如何有条件地呈现从调用 Firebase 函数的函数返回的值?

React Native: How to conditionally render a value returned from a function that calls Firebase function?

在我的 React Native 应用程序中,我有以下功能 returns 来自 Firebase 的值:

const func = () => {
  const a = useFirestoreCollection(
    userRepository
      .getRef()
      .collection('collection1')
      .doc('doc1')
  )
  return a.name;
}

然后组件看起来像这样:

return (
  <Text>
    {func()}
  </Text>
)

问题是,我想有条件地渲染它,像这样:

return (
  <Text>
    {func() ? func() : "backup"}
  </Text>
)

但这会引发错误 Rendered more hooks than during the previous render

如何实现这种条件渲染?

代码已经通过在嵌套函数中调用 useFirestoreCollection 打破了挂钩规则,因此用例无效。正常调用useFirestoreCollection作为钩子,检查返回值。

示例:

const a = useFirestoreCollection(
  userRepository
    .getRef()
    .collection('collection1')
    .doc('doc1')
);

...

return (
  <Text>
    {a?.name || "backup"}
  </Text>
);