【问题标题】:Object.assign() with Complex object Angular2 ngrx/storeObject.assign() 与复杂对象 Angular2 ngrx/store
【发布时间】:2017-07-19 01:06:23
【问题描述】:
import { Blog } from './app.model';
import { ActionReducer, Action } from '@ngrx/store';
import * as _ from 'underscore';

export const LOAD_BLOGS = 'LOAD_BLOGS';
export const SAVE_COMMENT = 'SAVE_COMMENT';

export interface AppState {
    blogs : Blog[]
}

export const initialState : AppState = {
    blogs : []
};

var a;

export const reducer = (state : AppState = initialState, action :Action) => {
    switch (action.type) {
        case LOAD_BLOGS:
            return Object.assign({}, state, {
                blogs : action.payload
            });

        case SAVE_COMMENT:
            const {title, comment} = action.payload;
            return state.blogs.map(states =>{
                    if(states.title === action.payload.title){
                    console.log(states);
                    return Object.assign({}, states ,{ comment : [...states.comment , action.payload.comment]});
                }
                return Object.assign({}, states);
            });

        default:
            return state;
    }
}

STORE BEFORE SAVE_COMMENT ACTION

{blogs : [{id: 1, "title" : "one", "comment" : ["oneC", "twoC"]}, {id: 2, "title" : "two", "comment" : ["oneC", "TwoC"]}]}

STORE AFTER SAVE_COMMENT ACTION WITH COMMENT "ThreeC" 到标题为 "two" 的博客

[{id: 1, "title" : "one", "comment" : ["oneC", "twoC"]},{id: 2, "title" : "two", "comment" : ["oneC", "TwoC", "ThreeC"]}]

应该包含对象数组的外部博客对象不存在,而是只有一个包含更新博客的对象数组。

【问题讨论】:

  • 如果您知道Object.assign(),那么您尝试过什么?
  • 如果很紧急,请尽可能让问题清楚,而不是添加紧急的文字。
  • 我已经更新了问题,请看..

标签: angular ecmascript-6 ngrx


【解决方案1】:

我建议你在你的 reducer 函数中加入一些简单的 console.logs,在你的 details 函数中加入 for 循环,看看它在做什么。

你的问题是你的 reducer 函数中有一个 map 遍历每个博客,然后在你的 details 函数中你再次循环所有博客,一旦找到匹配项就返回匹配项。

这意味着您循环播放每篇博文并将其替换为与博文标题匹配的博文(您将点击return Object.assign({},state,c);)。

您可以通过多种方式解决问题,但如果您喜欢自己的代码结构,您可以只将博客的状态传递给详细信息并删除 for 循环。

【讨论】:

    猜你喜欢
    • 2017-04-15
    • 2018-04-07
    • 2017-09-08
    • 2015-12-31
    • 1970-01-01
    • 2021-01-17
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多