2017-09-01 34 views
0

我正在學習React和redux的教程,但在視頻結束時,即使我有相同的代碼,我也會得到一個錯誤。已經答覆未捕獲TypeError:state.concat不是函數錯誤

遺漏的類型錯誤:state.concat不是一個函數

任何幫助將不勝感激!

//action is a parameter and the reducer is the function 
 
//We will make change to the state based on the action (function) 
 

 
//Function will be reducers 
 
const cards = (state, action) => { 
 
    switch (action.type){ 
 
     case 'ADD_CARD': 
 
      let newCard = Object.assign({}, action.data, { 
 
       score: 1, 
 
       id: +new Date 
 
      }); 
 
//error is here 
 
      return state.concat([newCard]); 
 
     default: 
 
      return state || {}; 
 
    } 
 

 

 
}; 
 

 
//Redux helper function to pass reducer functions 
 
const store = Redux.createStore(Redux.combineReducers({ 
 
    cards: cards 
 
})); 
 

 
//Keep an eye on the store for changes 
 
store.subscribe(() => { 
 
    console.log(store.getState()); 
 
}); 
 

 
//activate store action 
 
store.dispatch({ 
 
    type: 'ADD_CARD', 
 
    data: { 
 
     front: 'front', 
 
     back: 'back' 
 
    } 
 
}); 
 

 
//Another action 
 
store.dispatch({ 
 
    type: 'ADD_CARD', 
 
    data: {} 
 
});

回答

0

國家應該是一個對象,而不是一個數組,所以.concat不會進行這項工作。你將不得不做一些像state.cards.concat(foobar)。如果我在這裏錯了,請糾正我,但看看狀態並驗證它的類型。

+0

在此情況下是狀態的卡屬性,它是根據作者在視頻數組?感謝 –

+0

你能在調試器中檢查它並確認嗎?或者只是控制檯記錄它並將輸出發送給我。 – stevelacerda7

+0

你可以分享你正在談論的教程和完整的代碼嗎? – kevgathuku

0

我在卡片的默認級別返回一個對象{}而不是數組[]。

//action is a parameter and the reducer is the function 
 
//We will make change to the state based on the action (function) 
 

 
//Function will be reducers 
 
const cards = (state, action) => { 
 
    switch (action.type){ 
 
     case 'ADD_CARD': 
 
      let newCard = Object.assign({}, action.data, { 
 
       score: 1, 
 
       id: +new Date 
 
      }); 
 
     //splitting the state object into individual properties 
 
      return state.concat([newCard]); 
 
     default: 
 
      return state || []; 
 
    } 
 

 

 
}; 
 

 
//Redux helper function to pass reducer functions 
 
const store = Redux.createStore(Redux.combineReducers({ 
 
    cards: cards 
 
})); 
 

 
//Keep an eye on the store for changes 
 
store.subscribe(() => { 
 
    console.log(store.getState()); 
 
}); 
 

 
//activate store action 
 
store.dispatch({ 
 
    type: 'ADD_CARD', 
 
    data: { 
 
     front: 'front', 
 
     back: 'back' 
 
    } 
 
}); 
 
I wasn't reutning an array at the default in cards instead I had {}. I guest I was returning an object ? 
 

 

 
//Another action 
 
store.dispatch({ 
 
    type: 'ADD_CARD', 
 
    data: {} 
 
});

0

嘗試這個代碼

const cards = (state = [], action) => { 
    switch (action.type){ 
     case 'ADD_CARD': 
      let newCard = Object.assign({}, action.data, { 
       score: 1, 
       id: +new Date 
      }); 
      //error is here 
      return state.concat(newCard); 
     default: 
      return state || {}; 
    } 
}; 
相關問題