简体   繁体   中英

how to push into nested array in reducer

在此处输入图片说明

Above image shows what happens when I trying to dispatch a reply action.

Currently trying to push the input field value etc into the replyComments...but it is still empty even when dispatching this action.... the reducer is checking the majorIndex first and then the minorIndex, from there it should push it into the replyComments. Any one knows how I can fix this?

Link to working Codesandbox

 case types.REPLY_COMMENT: { return { ...state, enableToggleComment: true, imageData: state.imageData.map(image => image.id === action.majorIndex ? { ...image, comments: { [action.minorIndex]: { replyComments: [...image.comments.replyComments, { comment: action.newComment, likeComment: image.toggle, enableReply: false }] } } } : image ) } }

EDIT:

I know noticed it's due to a missing key to [action.minorIndex] and when using the ? operator and want to return an object you should add the parenthesis, otherwise you are declaring a scope (like i did whoops)

case types.REPLY_COMMENT: {
            return {
                ...state,
                enableToggleComment: true,
                imageData: state.imageData.map(image => image.id === action.majorIndex ?
                    ({   
                        ...image, 
                        comments: {
                            [action.minorIndex]: {
        replyComments: [...image.comments[action.minorIndex].replyComments, { comment: action.newComment, likeComment: image.toggle, enableReply: false }],
                            }
                        }
                    }) : image
                )
            }
        }

I've only added action.replyText but you should be able to add the rest now

case types.REPLY_COMMENT: {
    return {
        ...state,
        enableToggleComment: true,
        imageData: state.imageData.map(image =>
            image.id === action.generalIndex
            ? {
                ...image,
                comments: image.comments.map((comment, i) =>
                    i === action.majorIndex
                    ? {
                        ...comment,
                        replyComments: [
                            ...comment.replyComments,
                            action.replyText
                        ]
                    }
                    : comment
                )
            }
            : image
        )
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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