简体   繁体   English

如何在不发生变异的情况下替换状态?

[英]How to replace an state without mutating?

I am using React and Redux and i need to update my state with updated data.我正在使用 React 和 Redux,我需要用更新的数据更新我的状态。 My state contains an array of objects like this:我的状态包含一个像这样的对象数组:

[
    {
        "messages": [/*somedata*/],
        "users": [/*somedata*/],
        "avatar": "/*somedata*/",
        "_id": "/*somedata*/",
        "type": "/*somedata*/",
        "createdAt": "/*somedata*/",
        "__v": 0
    },
    {
        "messages": [/*somedata*/],
        "users": [/*somedata*/],
        "avatar": "/*somedata*/",
        "_id": "/*somedata*/",
        "type": "/*somedata*/",
        "createdAt": "/*somedata*/",
        "__v": 0
    }
]

So in this reducer, i just want to replace or update the entire state array with my payload but without mutate my state .所以在这个减速器中,我只想用我的有效载荷替换或更新整个状态数组,但不改变我的状态 My payload also contains the same array of objects as above but with updated data.我的有效负载还包含与上述相同的对象数组,但具有更新的数据。

const chatsReducer = (state = chats, {type, payload}) => {
  switch (type) {
    case '@updateChats':
        return state = payload //i need something like this but without mutating
    default:
        return state
  }
}

This should help you, it creates a new array and populates it with all the objects within your payload array.这应该对您有所帮助,它会创建一个新数组并使用payload数组中的所有对象填充它。

const chatsReducer = (state=chats, {type, payload}) => {
  switch (type) {
    case '@updateChats':
        return [ ...payload ];

    default:
        return [ ...state ];
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM