我想要将多个产品添加到Collection 夹屏幕,并从那里分别删除每个产品,但当我单击添加到Collection 夹按钮时,我只能添加一个产品,如果我添加另一个产品,该产品将替换未添加的前一个产品.

上下文代码

const initialState = {
  products: ProductData,
  cart: [],
  FavoritesList: [],
};
 
const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'ADD_PRODUCT_TO_FAVORITE':
      const product = action.payload;

      const index = state.FavoritesList.findIndex(
        (item) => item?.id === product?.id
      );

      if (index !== -1) {
        return {
          ...state,
          products: state.FavoritesList.filter((_, i) => i !== index),
        };
      } else {
        return {
          ...state,
          products: state.FavoritesList.concat(product,),
        };
      }

    case 'DELETE_FAVORITE_PRODUCT':
      return {
        ...state,
        products:state.products.filter((item)=> item?.id === product?.id)
      };
              
    case 'CLEAR':
      return { cart: [] }
           
    default:
      throw new Error(`unknow action.${action.type}`)
  }
}

Collection 夹屏幕代码

const Faviroute = () => {
  const { favorites, products } = useCart();
  const dispatch = useDispatch();

  const Clear = (index) => {
    dispatch({ type: "DELETE_FAVORITE_PRODUCT", index });
  };
 
  return (
    <View
      style={{
        flex: 1,
      }}
    >
      {(products.length === 0) ?
        <View>
          <Text>Just add the items you would & place your order here.</Text>
        </View>   
      : <View style={{flex:1,}}> 
          {/*Card Container*/}
          <ScrollView>
            <View>
              {products.map((item, index) => (         
                <View key={index}>  
                  <Image source={item.image} />
                  <TouchableOpacity onPress={() => Clear(item)}>
                    <Image source={icons.love} />
                  </TouchableOpacity>
                </View>
              ))}       
            </View>
          </ScrollView>
        </View>
      }
    </View>
  )
}

任何人都可以帮助我弄清楚我如何可以轻松地添加到Collection 夹中的每一个单独的产品,并从Collection 夹列表中删除每个最喜欢的产品分别?

推荐答案

如果你想让ADD_PRODUCT_TO_FAVORITE的动作变成102,一个接一个地将产品添加到Collection 列表中,而让DELETE_FAVORITE_PRODUCT的动作变成从Collection 列表中一个接一个地删除产品,那么我建议你重构如下:

  1. 确保DELETE_FAVORITE_PRODUCT reducer用例正确访问action payload,以获取要删除的已定义产品对象.
  2. 确保添加/删除Collection 夹是在state.favorites数组102 state.products数组上进行的,state.products数组是所有can受Collection 的产品的"真实性来源".
  3. 您正在将当前映射的item传递给clear处理程序,请确保对该参数进行一致的命名,以便清楚传递的是什么.

代码:

const initialState = {  
  products: ProductData,
  cart: [],
  favorites: [],
};

const reducer = (state = initialState, action) => {
  switch(action.type){
    case 'ADD_PRODUCT_TO_FAVORITE':
      const product = action.payload;

      const favorited = state.favorites.find(
        (item) => item?.id === product?.id
      );

      if (!favorited) {
        // Not favorited, add to favorites list
        return {
          ...state,
          favorites: state.favorites.concat(product),
        };
      }
      // Otherwise return current state
      return state;

    case 'DELETE_FAVORITE_PRODUCT':
      const { product } = action.payload; // <-- get product from payload

      const favorited = state.favorites.find(
        (item) => item?.id === product?.id
      );

      if (favorited) {
        // Favorited, remove from favorites list
        return {
          ...state,
          favorites: state.favorites.filter((item)=> item.id !== product.id)
        };
      }
      // Otherwise return current state
      return state;
              
    case 'CLEAR':
      return { ...state, cart:[] };
           
    default:
      console.log("Unhandled action", { action });
      return state;
  }
};
const Favorite = () => {
  const { favorites, products } = useCart();
  const dispatch = useDispatch();

  const unfavorite = (product) => {
    dispatch({
      type: "DELETE_FAVORITE_PRODUCT",
      payload: { product }, // <-- pass product in payload
    });
  };
 
  return (
    <View style={{ flex: 1 }}>
      {!products.length ? (
        <View>
          <Text>Just add the items you would & place your order here.</Text>
        </View>   
      ) : (
        <View style={{ flex: 1 }}>
          <ScrollView>
            <View>
              {products.map((product) => (         
                <View key={product.id}>  
                  <Image source={product.image} />
                  <TouchableOpacity onPress={() => unfavorite(product)}>
                    <Image source={icons.love} />
                  </TouchableOpacity>
                </View>
              ))}
            </View>
          </ScrollView>
        </View>
      )}
    </View>
  );
};

Javascript相关问答推荐

React Hooks中useState的同步问题

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

有条件的悲剧

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

使用i18next在React中不重新加载翻译动态数据的问题

Msgraph用户邀请自定义邮箱模板

在观察框架中搜索CSV数据

material UI按钮组样式props 不反射

在HTML语言中调用外部JavaScript文件中的函数

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

为什么我的自定义元素没有被垃圾回收?

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

如何找到带有特定文本和测试ID的div?

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

react 路由如何使用从加载器返回的数据

Chrome上的印度时区名S有问题吗?

有角粘桌盒阴影

使用VITE开发服务器处理错误

JS/css:将数字输入的S函数和可调整大小的元素S函数绑定在一起