2017-08-29 267 views
0

我想寫一個應用程序,用戶可以在其中添加一個項目到集合。用戶鍵入collection-item的名稱,並出現該名稱的項目。 但是,當我派遣行動addCollection減速機不知道我的狀態在反應減少

export function addCollection(text) { 
    console.log("ACTION ADD COLLECTION FIRED"); 
    return { 
     type: "ADD_COLLECTION", 
     text 
    } 
} 

我減速機:

export default function collection(state = [], action) { 
    switch(action.type) { 
     case "ADD_COLLECTION": 
     return (
      Object.assign({}, state, { 
       collections: [ 
        { 
         name: action.text, 
         src:'' 
        }, 
        ...state.collections 
       ] 
      }) 
     ); 

    } 
    return state 
} 

出錯:

TypeError: Cannot convert undefined or null to object 

它有我的減速器6行。我認爲減速機不知道我的狀態。收集

var initialState = { 
    collections:[ 
     { 
      name:"Aenean in justo ante", 
      src: '' 
     }, 
     { 
      name:"Aenean in justo ante", 
      src: '' 
     } 
    ], 
    formIsRender: false 
} 

const store = createStore(allReducers, initialState) 

錯誤在哪裏?

回答

3

您的初始狀態是array而不是object
您不能也不應該在陣列上使用Object.assign
雖然可以使用spread operator以便不改變數組。

試試這個:

case "ADD_COLLECTION": 
     return [...state, {name: action.text}] 

我注意到另一件事是,在初始狀態對象將其命名爲collections(複數)和你減速的名字是collection(單數)。
確保它不是拼寫錯誤。