【问题标题】:redux reducer spread operator on array not replacing old state数组上的redux reducer扩展运算符不替换旧状态
【发布时间】:2017-05-04 13:56:58
【问题描述】:

在我的 redux reducer 中,我两次更新专辑列表。我希望第二个列表覆盖提供的第一个列表,但是,这不起作用,并且专辑第二个调用都添加到第一个调用中。

下面的展开运算符有什么我做的不对吗?请在下面查看我的减速器。

export default (state = [], action) => {

    switch(action.type) {

    case 'GET_ALBUM_NAME_SUCCESS':

        return [
            ...state,
            ...action.albums.map(album => {
                const newAlbum = {...album};
                delete(newAlbum.selections);
                return newAlbum;
            })
        ];

    default:

        return state;
}

【问题讨论】:

  • 为什么你的状态是一个数组?
  • 我认为您确实在寻找return action.albums.map(({selections:_, ...newAlbum}) => newAlbum);。不要使用delete!

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

您不需要在要添加的值上使用扩展运算符,只要您要向状态添加值,

export default (state = [], action) => {

    switch(action.type) {

    case 'GET_ALBUM_NAME_SUCCESS':

        return [
            ...state,
            action.albums.map(album => {
                const newAlbum = {...album};
                delete newAlbum.selections;
                return newAlbum;
            })
        ];

    default:

        return state;
}

但是,如果您只想覆盖之前的状态,则根本不需要扩展运算符。

export default (state = [], action) => {

    switch(action.type) {

    case 'GET_ALBUM_NAME_SUCCESS':

        return [
            action.albums.map(album => {
                const newAlbum = {...album};
                delete newAlbum.selections;
                return newAlbum;
            })
        ];

    default:

        return state;
}

【讨论】:

  • Delete 不是一个函数,它是一个运算符,因此不需要这些括号并让它看起来不是。
  • @loganfsmyth 这就是我看到它时的疑惑。但由于问题不存在,我认为这可能是 OP 编写的内容
  • 是的,公平,只是认为值得一提 OP。
猜你喜欢
  • 2019-03-13
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2019-09-01
  • 2017-03-16
  • 2021-03-16
  • 1970-01-01
  • 2019-09-11
相关资源
最近更新 更多