【问题标题】:React Native , unable to add item in cart by using react -reduxReact Native,无法使用 react -redux 在购物车中添加商品
【发布时间】:2020-10-14 15:09:37
【问题描述】:

我使用 react native 和 redux 创建了一个购物车屏幕和商品列表,但是当我点击购买商品时,它没有添加到购物车中,也没有显示任何错误

下面是我存储项目列表的代码

牛仔裤.js

class Jeans extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.items}
          key={(items) => items.id.toString()}
          numColumns={2}
          renderItem={({ item }) => (
            <CardBuyItem>
              <Image style={styles.image} source={item.image} />
              <View style={styles.detailContainer}>
                <Text style={styles.title}>{item.title}</Text>
                <Text style={styles.subTitle} numberOfLines={1}>
                  {item.subTitle}
                </Text>
                <Text style={styles.price}>Rs {item.price}</Text>
              </View>
              <TouchableHighlight onPress={() => this.props.addToCart(item.id)}>
                <View style={styles.buy}>
                  <Text>Buy Once</Text>
                </View>
              </TouchableHighlight>
            </CardBuyItem>
          )}
        />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    items: state.clothes.jeans,
  };
};

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

下面是我的购物车屏幕代码,当用户点击时应该添加项目

cart.js

class Cart extends Component {
  render() {
    let addedItems =
      this.props.items && this.props.items.length ? (
        <FlatList
          data={this.props.items}
          key={(items) => items.id.toString()}
          numColumns={2}
          renderItem={({ item }) => (
            <View>
              <Image style={styles.image} source={item.image} />
              <View style={styles.detailContainer}>
                <Text style={styles.title}>{item.title}</Text>
                <Text style={styles.subTitle} numberOfLines={1}>
                  Quantity: {item.quantity}
                </Text>
                <Text style={styles.price}>Rs {item.price}</Text>
              </View>
              <TouchableOpacity>
                <View style={styles.buy}>
                  <Text>Remove</Text>
                </View>
              </TouchableOpacity>
            </View>
          )}
        />
      ) : (
        <View style={styles.emptyContainer}>
          <Text style={styles.empty}>There is Nothing in your Cart</Text>
        </View>
      );

    return (
      <View style={styles.container}>
        <View style={styles.order}>
          <Text style={styles.orderText}>You Order:</Text>
        </View>
        <View>{addedItems}</View>
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    items: state.addedItems,
  };
};

下面是我的代码缩减器和操作

reducer.js

export default function ClothesReducer(state = initialstate, action) {
  if (action.type === ADD_TO_CART) {
    let addedItem = state.jeans.find((item) => item.id === action.id);
    let existed_item = state.addedItems.find((item) => action.id === item.id);
    if (existed_item) {
      addedItem.quantity += 1;
      return {
        ...state,
        total: state.total + addedItem.price,
      };
    } else {
      addedItem.quantity = 1;
      let newTotal = state.total + addedItem.price;

      return {
        ...state,
        addedItems: [...state.addedItems, addedItem],
        total: newTotal,
      };
    }
  } else {
    return state;
  }
}

action.js

import { ADD_TO_CART } from "./ClothesActionType";

export const addToCart = (id) => {
  return {
    type: ADD_TO_CART,
    id,
  };
};

我试图找出问题所在,但找不到任何错误。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 调度了哪些操作,它们有哪些数据以及它们对状态做了哪些更改?您可以使用 redux devtools 来检查甚至只是 console.log 中间件:(store) =&gt; (next) =&gt; (action) =&gt; { console.log( 'action', JSON.stringify(action, undefined, 2) ); console.log( 'state', JSON.stringify(store.getState(), undefined, 2) ); setTimeout(() =&gt; console.log( 'new state:', JSON.stringify(store.getState(), undefined, 2) ) ); return next(action); };

标签: javascript reactjs react-native redux


【解决方案1】:

在 cart.js 中你应该替换它

const mapStateToProps = (state) => {
  return {
    items: state.addedItems,
  };
};

const mapStateToProps = (state) => {
  return {
    items: state.clothes.addedItems,
  };
};

【讨论】:

  • 它工作了 谢谢,我有不同的物品清单,比如衬衫、鞋子、食物我如何在let addedItem = state.jeans.find((item) =&gt; item.id === action.id); 这里添加它们
  • 我建议将所有布料放在一个数组中,但每个项目都有一个类别对象,以便识别更有意义。但这实际上取决于您的设置方式以及您想要实现的目标。
  • 所以需要在initialstate中创建和排列并将所有项目放入其中,如initialstat = {item:[jenas:{},shirts:{} ]},以及我如何访问它们,如state.clothes.item(jeans)
  • 假设你有几个像jeans=[], shirts=[] 这样的衣服数组然后制作initialstate = {items:[...jenas,...shirts]},每个牛仔裤或衬衫对象都可以有一个类别道具,其中有牛仔裤数组的默认值牛仔裤等等,然后@987654328 @得到牛仔裤数组
【解决方案2】:

你正在改变状态,here 是一些关于如何不这样做的信息。

我认为你的减速器应该是这样的:

export default function ClothesReducer(
  state = initialstate,
  action
) {
  if (action.type === ADD_TO_CART) {
    let addedItem = state.jeans.find(
      (item) => item.id === action.id
    );
    let existed_item = state.addedItems.find(
      (item) => action.id === item.id
    );
    const addedItems = existed_item
      ? state.addedItems.map((item) =>
          item === existed_item
            ? { ...item, quantity: item.quantity + 1 }
            : item
        )
      : [
          ...state.addedItems,
          { ...addedItem, quantity: 1 },
        ];
    return {
      ...state,
      addedItems,
      total: state.total + addedItem.price,
    };
  } else {
    return state;
  }
}

【讨论】:

  • 谢谢,我有不同的物品清单,比如衬衫、鞋子、食物我如何将它们添加到 let addedItem = state.jeans.find((item) => item.id === action 。ID);在这里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多