如何使用react将对象推入数组

时间:2017-07-19 04:35:58

标签: reactjs redux react-redux

这是我的初始状态常量对象,我正在尝试在注释中添加一个新的注释项,但是这段代码并没有将我的对象推入到我提前做错的地方。

    export const comments = [];

    export const BlogPostReducer = (state = comments, action) => {
        switch (action.type) {
            case 'ADD_COMMENT':
                return [
                ...state,
                {
                    name: action.comment.name,
                    subject: action.comment.subject,
                    message: action.comment.message
                }
            ];
            default:
                return state;
        }
    };
after i used see console here...still im getting empty state 

image here

4 个答案:

答案 0 :(得分:0)

要推送新对象,您需要执行

return [
    ...state,
    {
       name: action.comment.name,
       subject: action.comment.subject,
       message: action.comment.message
    }
];

这将创建新数组,将对象推入其中并将其返回

答案 1 :(得分:0)

如果要以不可变的方式将其添加到数组中,则应使用' concat'

尝试以下代码。

export const comments = [];

export const BlogPostReducer = (state = comments, action) => {
    switch (action.type) {
        case 'ADD_COMMENT':
            return state.concat({name: action.comment.name,subject: action.comment.subject,message: action.comment.message});
        default:
            return state;
    }
};

答案 2 :(得分:0)

这种方式我已经实现了,

const addCommentToArray = (state, action) => {
    return [...state.comments, {
        name: action.comment.name,
        subject: action.comment.subject,
        message: action.comment.message
    }];
}

export const BlogPostReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_COMMENT':
            return Object.assign({}, state, { comments: addCommentToArray(state, action) });

        default:
            return state;
    }
};

答案 3 :(得分:0)

您需要将注释传递给store作为参数并附加到注释中。

export const BlogPostReducer = (state, action) => {
    switch (action.type) {
        case 'ADD_COMMENT':
            let { comments } = state;
            comments = comments || [];
            comments.push(action.comment);
            state.comments = comments;
            return state;
        default:
            return state;
    }
};