【问题标题】:React Native Navigation: Conditionally render tab bar badge not working?React Native Navigation:有条件地渲染标签栏徽章不起作用?
【发布时间】:2021-02-03 01:02:14
【问题描述】:

我正在尝试为我的通知标签显示标签栏徽章。如果用户有通知,在后端编写通知后,我将用户“hasNotifications”的字段设置为true。单击通知选项卡后,我将“hasNotifications”设置为 false。

这是我的实现:

function renderBadge() {

  Firebase.firestore()
  .collection('users')
  .doc(Firebase.auth().currentUser.uid)
  .onSnapshot(function(doc) { 

      if (doc.data().hasNotifications) {
          console.log("true")
          return true
      }
      else {
          console.log("null")
          return null
      }
      
  })
}

 
//Bottom Tabs
function Tabs() {
  
  return (

    <Tab.Navigator
    initialRouteName="Home"
    tabBarOptions={{
      activeTintColor:"#FFFFFF",
      inactiveTintColor:"#696969",
      style: {
        backgroundColor: '#000000',
        borderTopColor: "transparent"
      },
    }}>

      <Tab.Screen 
        name="Notificaton" 
        component={Notification}
        options={{
          tabBarLabel: ' ',
          tabBarIcon: ({ color, size }) => (
            <Ionicons name="md-notifications" size={size} color={color} />
          ),
          tabBarBadge: renderBadge() <----- Render red dot if true, no red dot if null

        }}
      />  

    </Tab.Navigator>
  );
}

控制台日志显示监听器正在工作,并根据用户是否收到通知返回 true/null。但标签栏徽章不显示。我该如何解决这个问题?

编辑:看起来当我设置tabBarBadge: renderBadge() 时,徽章永远不会出现。当我设置tabBarBadge: renderBadge 时,徽章总是出现。侦听器工作正常,但事实并非如此。

编辑2:我把函数改成const renderBadge = () =&gt; {,还是不行。

【问题讨论】:

    标签: javascript react-native react-native-navigation


    【解决方案1】:

    我知道 react(对于浏览器)比 react-native 更好,但是如果范式相同,你应该改变以下几个方面:

    • 不要直接改变函数范围内的变量,而是使用useState来保存布尔值;更改其 setter 函数提供的值
      • 这将做出反应,以便在发生变化时注意到变化并做出反应。
    • 您的 Firebase 访问权限可能是某种副作用,因此您应该使用 useEffect,也许将 Firebase.auth().currentUser.uid 作为依赖项。

    结果可能类似于:

    function useNotificationsBadge() {
        const [hasNotifications, setHasNotifications] = useState(null);
        const userId = Firebase.auth().currentUser.uid;
    
        useEffect(
            () => Firebase.firestore()
                .collection('users')
                .doc(userId)
                .onSnapshot(function(doc) {
                    const newHasNotifications = doc.data().hasNotifications ? true : null;
                    setHasNotifications(newHasNotifications);
                }),
            [userId]
        );
    
        return hasNotifications;
    }
    

    然后你可以在你的组件中编写;

        ...
        const hasNotifications = useNotificationsBadge();
        ...
    
            tabBarBadge: hasNotifications
    

    我个人的建议是在这个 sn-p 中将 null 替换为 false 以使 API 更清晰。

    【讨论】:

    • 这些都是很好的考虑!我希望快照在用户激活应用时始终处于监听状态,这样如果添加了新通知,徽章就会在用户使用应用时显示!
    • 我添加了一些演示代码,展示了如何实现我的言论。
    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多