微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反应原生如何刷新篮子计数

如何解决反应原生如何刷新篮子计数

大家好,我正在尝试制作一个有篮子的应用程序。我用 React-native 、Mobx 和 AsyncStorage

当有人点击添加到购物篮到一个项目时,它会将其添加到 AsyncStorage 然后使用另一个函数计算购物篮计数。那一切正常,但是当我在产品页面并选择添加到购物篮到一个项目时。直到我按到另一个页面,篮子数量才会改变。

总结当这个方法调用时,我必须重新渲染标签栏。谢谢

添加功能

@action async AddproductToBasket(product,Count) {
    try { 
      const con = {product,Count};
      const tempProduct = [];

      await AsyncStorage.getItem('basket').then((basket) => {
       
        console.log(basket);
        tempProduct.push(con);
        if (basket) {
          tempProduct.push(...JSON.parse(basket));
        }

        this.basketCount = tempProduct.length;
      });

      await AsyncStorage.setItem('basket',JSON.stringify(tempProduct));
    } catch (e) {
      console.log(e);
    }
  }

计数

@observable basketCount = 0;


@action async basketCount() {
    try {
        AsyncStorage.getItem('basket').then((basket) => {
          const tempBasket = [];
          if (basket) {
            tempBasket.push(...JSON.parse(basket));
          }          
      runInAction(() => {
          this.basketCount = tempBasket.length;
       
      });         
        });      
    } catch (e) {
      console.log(e);
    }
  }

这也是我的标签

function TabBar({state,descriptors,navigation}) {

  var Count = AuthStore.basketCount;
  return (
    <Box
      pb={20}
      bg="white"
      flexDirection="row"
      style={{
        shadowColor: '#000',shadowOpacity: 0.1,shadowRadius: 20,}}>
      {state.routes.map((route,index) => {
        const {options} = descriptors[route.key];

        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',target: route.key,});         
                       if (!isFocused && !event.defaultPrevented) {
            
            navigation.navigate(route.name);
          }
        };
        return label === 'Main' ? (
          <Box
            key={label}
            p={15}
            mt={-38}
            bg={'menuBgColor'}
            style={{shadowColor: 'green'}}
            borderColor="red"
            borderRadius="full">
            <Button size={60} bg="#053EA1" borderRadius="full" onPress={onPress}>
             (
                <TabOrtaFocusedSVG
                  color={isFocused ? theme.colors.red : theme.colors.textLight}
                />
              ) 
            </Button>
          </Box>
        ) : (
          // tab-button
          <Button
            key={label}
            pt={6}
            flexDirection="column"
            height={56}
            flex={1}
            onPress={onPress}>
            {label === 'Main2' && (
              <Tabmenu1
                color={isFocused ? theme.colors.red : theme.colors.textLight}
              />
            )}           

            {label === 'Basket' && (
              <Box
                position="absolute"
                top={10}
                right={10}
                height={20}
                width={20}
                borderRadius={400}
                bg="#FF1616"
                justifyContent="center"
                alignItems="center">
                <Text>{Count}</Text>
              </Box>
            )}

            {/* indicator */}
            <Box
              size={4}
              bg={isFocused ? 'red' : 'white'}
              mt={6}
              borderRadius="full"
            />
          </Button>
        );
      })}
    </Box>
  );
}

export default TabBar;

包装

"mobx": "^6.1.4","mobx-react": "^7.1.0","popup-ui": "^1.2.2","react": "16.13.1","react-native": "0.63.4",

解决方法

我认为您可能会在 AddproductToBasket 函数中覆盖 this.basketCount。

你必须尝试用basketCount的新值增加旧值

喜欢:

this.basketCount += tempProduct.length;

另外,尝试在 TabBar 组件中添加观察者来监听 mobx 状态更新,如下所示:

import { observer } from "mobx-react-lite" // Or "mobx-react".

const TabBar = observer(({state,descriptors,navigation}) => {

  var Count = AuthStore.basketCount;
  return (
    <Box
      pb={20}
      bg="white"
      flexDirection="row"
      style={{
        shadowColor: '#000',shadowOpacity: 0.1,shadowRadius: 20,}}>
      {state.routes.map((route,index) => {
        const {options} = descriptors[route.key];

        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',target: route.key,});         
                       if (!isFocused && !event.defaultPrevented) {
            
            navigation.navigate(route.name);
          }
        };
        return label === 'Main' ? (
          <Box
            key={label}
            p={15}
            mt={-38}
            bg={'menuBgColor'}
            style={{shadowColor: 'green'}}
            borderColor="red"
            borderRadius="full">
            <Button size={60} bg="#053EA1" borderRadius="full" onPress={onPress}>
             (
                <TabOrtaFocusedSVG
                  color={isFocused ? theme.colors.red : theme.colors.textLight}
                />
              ) 
            </Button>
          </Box>
        ) : (
          // tab-button
          <Button
            key={label}
            pt={6}
            flexDirection="column"
            height={56}
            flex={1}
            onPress={onPress}>
            {label === 'Main2' && (
              <Tabmenu1
                color={isFocused ? theme.colors.red : theme.colors.textLight}
              />
            )}           

            {label === 'Basket' && (
              <Box
                position="absolute"
                top={10}
                right={10}
                height={20}
                width={20}
                borderRadius={400}
                bg="#FF1616"
                justifyContent="center"
                alignItems="center">
                <Text>{Count}</Text>
              </Box>
            )}

            {/* indicator */}
            <Box
              size={4}
              bg={isFocused ? 'red' : 'white'}
              mt={6}
              borderRadius="full"
            />
          </Button>
        );
      })}
    </Box>
  );
}
})

export default TabBar;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。