从嵌套的redux状态中删除元素 [英] Remove element from nested redux state

查看:92
本文介绍了从嵌套的redux状态中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的redux状态中删除一个元素.我使用无缝不可变及其API对状态进行操作.但是我找不到在嵌套状态时删除元素的任何好方法.

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.

所以我要删除的元素是: state.shoppingcartReducer.products[articleNr]

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

谢谢!

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,
  }
}

推荐答案

我回来的时候也遇到了类似情况.

I was stuck in a similar situation sometime back.

因此,根据 redux文档,更新嵌套对象的方式是:-

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.

第一种方法(困难的方法)

自行创建一个新对象并更新状态并返回新状态.现在,这里的关键是创建一个新的状态对象,而不将您的当前状态分配给该新对象,否则它将被突变.

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 ={}

现在为您分配不想更改为新状态的当前状态值.说在您的状态下,您有3个键,分别是key1key2和不想更改的shoppingCardReducer键.key1key2您不希望更改此操作.

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']={}

现在阅读state.shoppingReducers.products并在产品数组上进行sttart循环,并从状态中替换该特定元素,保持完好无损.

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)

如果您发现这显然是一种不好的方法,而不是真正的hack,则减速器与传播运算符会做同样的事情,但肯定是一种不好的方法.因此,我想尝试下一个选择.

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.

第二种方式(immutablejs)

我建议您使用 immutable.js .它真的很容易使用.

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

使用不可变,您可以使用deleteIn函数从状态中删除特定的特定产品元素.

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:我还没有尝试过上面的代码,但是只要稍加修改就可以了.希望您能理解.

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

第三种方法(Normalizr)

您还可以尝试对API响应进行规范化,以使您的数据变得平坦并可以访问.

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.

这篇关于从嵌套的redux状态中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆