首页 > 解决方案 > React Native,如何再次使 redux 状态为 false

问题描述

我创建了一个查看购物车,在其中显示总价和查看购物车按钮,当我添加项目时,它使条件为真并在每个屏幕下方显示该购物车,但是当我单击查看购物车时,它不会再次使其为假,我该怎么办这?有人可以检查我的代码并告诉我。下面是我的代码

Viewcart.js

<View>
        {this.props.show && this.props.items.length > 0 ? (
          <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");
                  this.props.show;
                }}
              >
                View Cart
              </Text>
            </View>
          </View>
        ) : null}
      </View>
const mapStateToProps = (state) => {
  return {
    show: state.clothes.show,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    showCart: () => dispatch(showCart()),
  };
};

减速器.js

if (action.type === SHOW_CART) {
    let addedItem = state.addedItems;
    if (addedItem.length === 0) {
      return {
        ...state,
        show: state.showCart,
      };
    } else {
      return {
        ...state,
        show: action.showCart,
      };
    }
  }
const initialstate = {
  showCart: false
}

动作.js

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

标签: javascriptreactjsreact-nativereact-redux

解决方案


根据聊天,要求是在退出屏幕时切换它,所以最简单的方法是使用生命周期方法。

隐藏使用 componentDidMount

componentDidMount(){
 this.props.showCartOff(); 
}

显示使用组件

componentWillUnmount(){
  this.props.showCart();
}

推荐阅读