Remove element from nested redux state

2019-01-20 05:21发布

I want to remove a element from my redux state. Im using seamless-immutable and its API to operate on the state. But I couldn't find any nice looking way to delete a element when the state is nested.

So the element I want to delete is: state.shoppingcartReducer.products[articleNr]

Thanks!


import Immutable from 'seamless-immutable'

import { addToShoppingcart, createShoppingCart } from '../actions/shoppingcartActions'

const CREATE_SHOPPING_CART = 'CREATE_SHOPPING_CART'
const ADD_PRODUCT = 'ADD_PRODUCT'
const DELETE_PRODUCT = 'DELETE_PRODUCT'
const UPDATE_QUANTITY = 'UPDATE_QUANTITY'
const SUMMARY = 'SUMMARY'

const initialState = Immutable({
  summary: {
    sum: 0,
    quantity: 0
  }
})

export default function shoppingcartReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_PRODUCT:
      return state
        .setIn(['products', action.product.articleNr], addArticle(action))

    // case DELETE_PRODUCT:
    //   return ??

    case SUMMARY:
      return state
        .set('summary', calculateSums(action, state))

    case CREATE_SHOPPING_CART:
      return state
        .set(action.id, createCart(action))

    case UPDATE_QUANTITY:
      return state.
        set('summary', calculateQuantity(action, state))
  }
  return state
}

function addArticle(action) {
  return {
    product: action.product
  }
}

function calculateQuantity(action, state) {
  return {
    quantity: state.summary.quantity + action.quantity
  }
}

function calculateSums(action, state) {
  return {
      sum: state.summary.sum + action.price,
      quantity: state.summary.quantity + action.quantity
  }
}

function calculateSumsDelete(action, state) {
  return {
      sum: state.summary.sum - action.product.price,
      quantity: state.summary.quantity - action.product.quantity
  }
}

function createCart(action) {
  return {
    id: action.id,
  }
}

2条回答
够拽才男人
2楼-- · 2019-01-20 05:54

I was stuck in a similar situation sometime back.

So according the redux docs the way you update nested object is :-

function updateVeryNestedField(state, action) {
    return {
        ....state,
        first : {
            ...state.first,
            second : {
                ...state.first.second,
                [action.someId] : {
                    ...state.first.second[action.someId],
                    fourth : action.someValue
                }
            }
        }
    }
}

But since you have array in your state it makes you work bit more difficult.

So there are 2 ways in which you can do this.

First way(The hard way)

Create a new object on your own and update the state and return the new state. Now the key here to create a new state object and not assign your current state to the the new object else it would be mutated.

So, create a new object .

const newState ={}

Now assign you current state values which you dont want to change to the new state. Say in your state you have 3 keys , key1, key2 which you dont want this action to change and shoppingCardReducer which you want to change.

newState['key1']=//key1 value from current state
newState['key2'] = //key2 value from current state

Now, try following:-

newState['shoppingCardReducer'] ={}
newState['shoppingCardReducer']['products']={}

Now read state.shoppingReducers.products and sttart looping over your products array and replace that particular element from the state, keep rest intact.

Then return the new state(You should keep rest of properties intact else your app can break)

If you see this is clearly a bad way to do it, not really a hack, reducers do same thing with spread operator but surely a bad way.So I would say try out next option.

Second way(immutablejs)

I would suggest you to use immutable.js. Its really easy and clean to use .

With immutable you can use deleteIn function to remove your particular particular product element from your state.

data.deleteIn(["shoppingcartReducer",product,//your_to_deleted_element_index])

P.S: I havent tried the above code but with little modification it should work. I hope you get the logic.

Third Method(Normalizr)

You can also try make to normalize your API response to make your data flat and access to access.

But among above three I feel immutable is the best option.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-20 05:59

You can simply use the delete method:

delete this.props.register_reducer.selected_products['yourid'];

查看更多
登录 后发表回答