尝试从具有对象的数组中删除元素

时间:2020-10-29 14:36:37

标签: javascript react-native redux react-redux

我想编写一个reducers函数来删除数组的元素。数组如下所示:

Array [
  Object {
    "category": "First Course",
    "id": 0,
    "name": "Feta im Backofen gratiniert",
    "price": 9.8,
  },
  Object {
    "category": "First Course",
    "id": 1,
    "name": "Feta gebacken in der Kruste",
    "price": 9.8,
  },
  Object {
    "category": "First Course",
    "id": 2,
    "name": "Frischer Oktapus",
    "price": 9.8,
  }]

这是我的减速器类:

const initialState = {
    restaurantId:0,
    cartItems:[],
    tableNumber:0,
}

const reducers = (state = initialState, action) => {
    switch (action.type) {
        case 'UPDATE_ID':
            return {
                ...state,
                restaurantId: action.payload
            };
        case 'ADD_ITEM_TO_CART':
            return {
                ...state,
                cartItems:[...Object.assign([],{...state.cartItems}),action.payload.item]
            };
        case 'UPDATE_TABLE_NUMBER':
            return{
                tableNumber: action.payload
            };
        case 'REMOVE_ITEM_FROM_CART':
            console.log(action.payload,state.cartItems);
            return{
                ...state,
                cartItems: state.cartItems.splice(action.payload,1)

            }
    }
    return state
}

export default reducers;

当我呼叫“ REMOVE_ITEM_FROM_CART”情况时,会发生不同的事件。有时会删除多个数组元素,有时会删除正确的数组元素。我不知道这是什么问题。我也console.log action.payload给出我要删除的数组元素的索引。始终是正确的有效载荷。

编辑:这是在其中调用操作的组件:

 import React from "react";
    import { StatusBar } from "expo-status-bar";
    import { NavigationActions } from "react-navigation";
    import { ImageBackground, StyleSheet, View, Text, TextInput, TouchableOpacity } from "react-native";
    import ShoppingBag from "../components/ShoppingBag";
    import {connect} from 'react-redux';
    
    class ShoppingBagScreen extends React.Component {
    
        returnOptionsShoppingBag=()=>{
            if(this.props.cartItems.length===0 ||typeof this.props.cartItems.length===undefined) {
                    return(
                        <View>
                            <Text style={{fontSize:20}}>Ihr Warenkorb ist leer</Text>
                        </View>
                    )
                }else{
                return(
                    <View>
                <ShoppingBag shoppingBag={this.props.cartItems} onPress={this.props.deleteCartItem}/>
                <Text/>
                        {this.viewOrderButton()}
                    </View>
    
                )}
        };
    
        viewOrderButton(){
            if(this.props.tableNumber>0){
            return(
            <View>
            <TouchableOpacity >
                <Text style={{fontSize:20, color:'red'}}>Kostenpflichtig bestellen</Text>
            </TouchableOpacity>
            </View>
            )}else{
            return(
                <View>
                    <TouchableOpacity onPress={this.orderAlert}>
                    <Text style={{color:'red',opacity:0.3,fontSize:20}}>Kostenpflichtig bestellen</Text>
                    </TouchableOpacity>
                </View>
                )}
            };
    
        orderAlert(){
            return(
                alert('Bitte wählen Sie eine Tischnummer')
            )
        }
    
        render() {
            return (
                <View style={styles.Background}>
                    <Text style={{fontSize:20}}>Ihre Tischnummer lautet: {this.props.tableNumber}</Text>
                    <Text/>
                    {this.returnOptionsShoppingBag()}
                </View>
            )
        }
    
    
    }
    
    
    function mapDispatchToProps(dispatch){
    
        return {
            deleteCartItem: (index) => dispatch({type: 'REMOVE_ITEM_FROM_CART', payload: index})
        }}
    
    function mapStateToProps(state){
        return{
            cartItems: state.cartItems,
            tableNumber: state.tableNumber
            }
        }
    
    
    export default connect(mapStateToProps,mapDispatchToProps)(ShoppingBagScreen);
 

这是ShoppingBag组件:

import React from 'react';
import {View,Text,TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

export default class ShoppingBag extends React.Component{

    renderShoppingBag = (shoppingBag)=>{
        return shoppingBag.map((item,index)=>{
            return(
                <View key={index} style={{flexDirection:'row'}}>
                    <Text style={{fontSize:20}}> {item.name} {item.price}0€     </Text>
                    <TouchableOpacity onPress={()=>this.props.onPress(index)}>
                    <Icon name='trash' size={20}/>
                    </TouchableOpacity>
                </View>
            )
        })
    }

    render() {
        return(
            <View>
            {this.renderShoppingBag(this.props.shoppingBag)}
            </View>
        )
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

首先,建议您将数组操作从return语句中拉出。

实际上,我强烈建议在每种情况下都将状态对象和数组的副本设置为第一要务。

case 'REMOVE_ITEM_FROM_CART':
  let cartAfterRemove = [...state.cartItems];
  cartAfterRemove.splice(action.payload, 1);
  //to confirm successful splice;
  console.log(cartAfterRemove);
  let newState = {...state, cartItems: cartAfterRemove};
  return newState;
}

如果您不小心嵌套项目并设置0突变,redux可能会变得非常时髦。您也可以发送对象的ID而不是索引的ID,但这将需要更多的重构。

https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns <-有一些很好的例子。

答案 1 :(得分:0)

有效负载应为项目的索引,因为拼接适用于索引,而不是要删除的项目数

相关问题