我正在学习一个课程,以学习在codePen上进行redux编码,但是,出现了以下错误。
redux.min.js:1 Uncaught TypeError: Cannot read property 'name' of undefined
at policies (pen.js:61)
at redux.min.js:1
at Array.forEach (<anonymous>)
at redux.min.js:1
at e.combineReducers (redux.min.js:1)
at pen.js:73
它告诉我,这是因为策略化简函数的名称无法读取action.payload.name,因为它是未定义的。我没有看到教练有同样的问题,但是我忠实地检查了我的代码,它和他的代码相同。我只是不明白如何解决它才能正确显示状态。
我已经调试并尝试解决该问题,但是到目前为止,除非我从策略缩减程序功能中删除action.payload.name,否则代码始终会引发错误。
console.clear();
// people dropping off a form (Aaction Creator)
const createPolicy =(name, amount)=>{
// console.log(name,amount,'test createpolicy')
return { // Action (a form in our analogy)
type:'CREATE_POLICY',
payload: {
name:name,
amount: amount
}
};
};
const deletePolicy = (name) =>{
return {
type:'DELETE_POLICY',
payload:{
name: name
}
}
}
const createClaim = (name, amountOfMoneyToCollect) =>{
return {
type:'CREATE_CLAIM',
payload:{
name: name,
amountOfMoneyToCollect: amountOfMoneyToCollect
}
};
};
// Reducers (Departments!)
// default oldListOfClaims=[] is for initial state.
const claimsHistory=(oldListOfClaims=[], action)=>{
if(action.type==="CREATE_CLAIM"){
// we care about this action (FORM!)
return [...oldListOfClaims, action.payload];
}
// we don't care the action (FORM!)
return oldListOfClaims;
};
const accounting=(bagOfMoney=100, action)=>{
if(action.type==='CREATE_CLAIM'){
return bagOfMoney - action.amountOfMoneyToCollect;
}
else if(action.type==='CREATE_POLICY'){
return bagOfMoney + action.payload.amount;
}
return bagOfMoney;
}
const policies = ( listOfPolicies = [], action)=>{
if(action.type = 'CREATE_POLICY'){
console.log( action.payload,'test playload name')
return [...listOfPolicies,action.payload.name]
}
else if(action.type='DELETE_POLICY'){
return listOfPolicies.filter(name =>
name!==action.payload.name);
}
return listOfPolicies;
};
const { createStore, combineReducers} = Redux;
const ourDepartments = combineReducers ({
accounting: accounting,
claimsHistory: claimsHistory,
policies: policies
})
const store = createStore(ourDepartments);
console.log(store)
store.dispatch(createPolicy('Alex', 20));
store.dispatch(createPolicy('Jim', 30));
store.dispatch(createPolicy('Bob', 40));
console.log(store.getState());
在将新名称和新金额发送到商店之后,我希望看到当前状态的console.log。并找出为什么继续出现此错误。
答案 0 :(得分:0)
查看您的policies
减速器-在检查类型时要分配而不是与操作类型进行比较。将其更新为以下代码:
const policies = ( listOfPolicies = [], action)=>{
// previously if(action.type = 'CREATE_POLICY'){
if(action.type === 'CREATE_POLICY'){
console.log( action.payload,'test playload name')
return [...listOfPolicies,action.payload.name]
}
// previously else if(action.type='DELETE_POLICY'){
else if(action.type==='DELETE_POLICY'){
return listOfPolicies.filter(name =>
name!==action.payload.name);
}
return listOfPolicies;
};