2017-07-19 131 views
0

這是我的初始狀態常量對象,我試圖將新的註釋項添加到註釋中,但此代碼不會將我的對象推入其中,提前。如何使用反應將對象推入數組

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

+0

@Hana Alaydrus你能幫助我在此 – kumar

回答

0

對於推新對象,你需要做的是

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

這將創建和新的數組,推對象,並返回其

+0

嗨,你可以檢查我重視我的問題你的代碼 – kumar

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; 
    } 
}; 
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; 
    } 
}; 
0

您需要通過評論來存儲作爲參數,並追加到評論。

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; 
    } 
}; 
+0

的使用後,這是一個非常糟糕的方法,因爲它發生變異狀態控制檯圖像。 @庫馬爾的答案要好得多。 –