首页 > 解决方案 > React Native,组件未关闭

问题描述

我创建了一个带有 react native 和 redux 的购物应用程序,我遇到了一个问题,当用户单击购买时,它应该在底部查看一个组件,该组件将显示总金额并查看购物车按钮,并且当用户从购物车中删除商品并且购物车为空时,它应该关闭/状态设置为 false,但它不会消失。谁能告诉我出了什么问题,下面是我的代码 reducer.js

 if (action.type === SHOW_CART) {
    let addedItem = state.jeans.find((item) => item.id === action.id);
    if (addedItem == 0) {
      return {
        ...state,
        show: console.log(state.showCart),
      };
    } else {
      return {
        ...state,
        show: console.log(action.showCart),
      };
    }
  }
const initialstate = {
  showChart: false,
}

那是我正在处理该功能的减速器

动作.js

export const showCart = (id) => {
  return {
    type: SHOW_CART,
    showCart: true,
    id,
  };
};

这就是我的行动,我描述它的行动

ViewCart.js

 <View>
        {this.props.show ? (
          <View style={styles.total}>
            <Text style={styles.totaltext}>Total:</Text>
            <Text style={styles.priceTotal}>{this.props.total}</Text>
            <View style={styles.onPress}>
              <Text
                style={styles.pressText}
                onPress={() => RootNavigation.navigate("Cart")}
              >
                View Cart
              </Text>
            </View>
          </View>
        ) : null}
      </View>
const mapStateToProps = (state) => {
  return {
    total: state.clothes.total,
    show: state.clothes.show,
  };
};

这就是我使用减速器的功能

标签: javascriptreactjsreact-nativereact-redux

解决方案


在我看来,问题出在你的 reducer.js 文件中

if (action.type === SHOW_CART) {
    let addedItem = state.jeans.find((item) => item.id === action.id);
    if (addedItem.quantity > 0) {
      return {
        ...state,
        showCart: action.showCart, // here was the problem
      };
    }
 }
 const initialstate = {
     showChart: false,
 }

请尝试一下并告诉我发生了什么。让我建议在您的if语句中添加另一个测试: if (addedItem && addedItem.quantity > 0) 避免意外操作可能造成的麻烦


推荐阅读