我正在关注React和redux的教程,但是在视频结尾处我得到了一个错误,即使我有相同的代码。
未捕获的TypeError: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 :(得分:0)
State应该是一个对象,而不是一个数组,所以.concat不会对它起作用。您必须执行state.cards.concat(foobar)之类的操作。如果我在这里错了,请纠正我,但要看看状态并验证其类型。
答案 1 :(得分: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: {}
});
答案 2 :(得分: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 || {};
}
};
答案 3 :(得分:0)
State.Cards.Concat(newCard); 您的阵列是Cards not state。