【问题标题】:How to update the state of badge counter in Tab Navigator in react-native如何在 react-native 中更新 Tab Navigator 中徽章计数器的状态
【发布时间】:2020-03-27 19:06:32
【问题描述】:

我使用 createBottomTabNavigator 作为标签栏。并且在通知的标签栏中,计数由自定义构建徽章显示。问题是每当更新通知时,标签栏中图标的计数不会改变。我必须导航单击任何其他项目以更新计数。我使用 AsyncStorage 将计数存储在通知组件中,并在客户组件中获取该计数,该组件在 tabnavigator 中调用。

class TabNotificationCount extends Component {

    constructor(props) {
        super(props);
        this.state = {
            focus: false,
            notificationCount: 0,
        }
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ focus: nextProps.isfocus })
        AsyncStorage.getItem('@count', (err, value) => {
            this.setState({ notificationCount: value })
            console.log("value-notification", this.state.notificationCount);
        })
    }

    render() {
        const { notificationCount } = this.state;
        const icon = this.state.focus ? require('../../../images/bell-active.png') : require('../../../images/bell-active.png');
        return (
            <View style={{ flexDirection: 'row' }}>
                <Image source={icon} style={{ width: 22, height: 22, }} />
                <Text style={{ position: 'absolute', top: -10, right: -15, borderRadius: 10, backgroundColor: 'red', color: '#fff', }}>{" " + notificationCount + " "}</Text>
            </View>
        );
    }

}

【问题讨论】:

  • 分享你的代码
  • @DevAS 请看一下代码。
  • 是否可以使用 {} 标签共享您的代码?很难读。
  • @Gyepesto 不幸的是我无法访问我的电脑,所以我通过手机上传代码,因此对齐不正确。
  • @Gyepesto 不幸的是我无法访问我的电脑,所以我通过手机上传代码,因此对齐不正确。

标签: react-native navigation react-native-navigation tabnavigator


【解决方案1】:

你在这里做得很好,它帮助了我,也解决了你描述的问题,我所做的是我刷新了导航参数以更新徽章,我不确定它的流程是什么,但刷新参数确实为我工作。

我在应用程序中有一个购物车页面,它允许删除/更新项目和底部标签导航器,因此每次删除/更新项目时我都需要刷新底部标签购物车图标总数。所以要实现它,我需要通过设置参数值之一来刷新导航参数(我认为这不是正确的方法,但它确实有效)。

下面是我用来解决问题的代码sn-ps。

在我的 cartIcon.js 中

import React, {Component} from 'react';
import {View, TouchableOpacity, ActivityIndicator , Image , AsyncStorage} from 'react-native';
import styles from '../styles';
import Text from '../reuseableComponents/Text';
import Icon from 'react-native-vector-icons/FontAwesome';  

export class IconCart extends Component {


  constructor(props) {
        super(props);
        this.state = {
            // focus: false,
            cartData: [],
        }
  }

   componentWillReceiveProps(nextProps) {
        // this.setState({ focus: nextProps.isfocus })
        AsyncStorage.getItem('cartData', (err, value) => {
            if(value){
                this.setState({ cartData: JSON.parse( value ) })
            }
        })
    }

  render() {
    return (
      <TouchableOpacity 
        activeOpacity={1}
        onPress={()=>{this.props.navigation.navigate('Cart')}}
      >
              { this.state.cartData.length != 0  &&
              <Text
                style={{
                  backgroundColor: 'red',
                  alignSelf: 'flex-end',
                  color: '#fff',
                  fontSize: 8,
                  zIndex: 1,
                  position: 'absolute',
                  width: 15,
                  textAlign: 'center',
                  bottom: 15,
                  height: 15,
                  paddingTop:2,
                  borderRadius: 8,
                  marginLeft:15,
                }}>
                {this.state.cartData.length}
              </Text>
              }            
            <Icon name={"shopping-cart"} color={this.props.color} size={24}/>
       </TouchableOpacity>
    );
  }
}

export default IconCart;

在我的购物车.js 中

  addQty = async(id) => {
    this.props.dispatch({type: 'CARTACTION', data: id, action: 'add', cartItems: cartData});//to update and refresh state in component
    await AsyncStorage.setItem('cartData', JSON.stringify(cartData));// set data in async storage
    this.props.navigation.setParams({cart: cartData.length});//to refresh navigation params
  };
  minusQty = async(id) => {
    this.props.dispatch({type: 'CARTACTION', data: id, action: 'sub', cartItems: cartData});
    await AsyncStorage.setItem('cartData', JSON.stringify(cartData));
    this.props.navigation.setParams({cart: cartData.length});
  };
  delItem = async(id) => {
    this.props.dispatch({type: 'CARTACTION', data: id, action: 'remove', cartItems: cartData});
    await AsyncStorage.setItem('cartData', JSON.stringify(cartData));
    this.props.navigation.setParams({cart: cartData.length});
  };

在bottomTabnavigator堆栈中的navigator.js中,将购物车放入标签栏图标

    Cart: {
      screen:cartStack,
      navigationOptions:({navigation}) => ({
        tabBarOptions: { 
            activeTintColor: '#142333',
            inactiveTintColor: '#778089',
            // showLabel:false,
            activeBackgroundColor:'#fff',
            inactiveBackgroundColor:'#fff',
            style:{height:64},
            labelStyle:{paddingBottom:10,paddingTop:0,marginTop:0},
        },
        tabBarIcon:({tintColor})=>(  
              // <Icon name="shopping-cart" color={tintColor} size={24}/>  
              <IconCart 
                color={tintColor} 
               />
          )  
       }),
    },

And at the end this is my first stackoverflow answer . So please consider any mistake as a part of a baby step towards community :).  

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多