Reactjs array.includes()不是函数
它在第一次单击时起作用,但当我再次单击以取消选择它时,它会显示错误: state.selectedStudents.includes不是函数。(在 'state.selectedStudents.includes(action.item)', “state.selectedStudents.includes”未定义)Reactjs array.includes()不是函数,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,它在第一次单击时起作用,但当我再次单击以取消选择它时,它会显示错误: state.selectedStudents.includes不是函数。(在 'state.selectedStudents.includes(action.item)', “state.selectedStudents.includes”未定义) 你直接改变了你的状态。使用filter和数组扩展运算符,而不是splice和push: switch (action.type) { case SELECT: retu
你直接改变了你的状态。使用
filter
和数组扩展运算符,而不是splice
和push
:
switch (action.type) {
case SELECT:
return {
...state,
selectedStudents: state.selectedStudents.includes(action.item)
? state.selectedStudents.filter(
student => student.id !== action.item.id
)
: [...state.selectedStudents, action.item]
};
default:
return state;
}
返回数组的新长度,而不是列表。因此,下次尝试时,类型编号没有包含方法。首先,state.selectedStudents.includes不是函数。表示
state.selectedStudents
不是数组。那是什么呢
.push()
不返回数组,它返回推后数组的长度。基于:
Array.push()返回值:调用方法的对象的新length
属性
因此,在第一次选择操作后,您的状态会发生以下变化:
state = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: 1, // <- it's a number, not an array.
}
在任何情况下,我都不会鼓励改变redux状态。这是我的建议
const selectReducer=(state=initialState,action)=>{
开关(动作类型){
案例选择:{
让selectedStudents=[…state.selectedStudents];
if(!\u.isEmpty(selectedStudents)和&selectedStudents.includes(action.item)){
const itemIndex=selectedStudents.indexOf(action.item);
selectedStudents=selectedStudents.splice(itemIndex,1);
}否则{
选择学生。推送(动作。项目);
}
返回{
……国家,
经过挑选的学生,
};
}
违约:
返回状态;
}
};
请提供一个。您仍然在使用这里的splice
改变原始状态。您是对的,我的重点是.push()
而没有注意到.splice()`。更新答案,谢谢!
state.selectedStudents.push(action.item)
state = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: 1, // <- it's a number, not an array.
}
switch (action.type) {
case SELECT:
return {
...state,
selectedStudents: state.selectedStudents.includes(action.item) ?
state.selectedStudents.filter(student => student.id !== action.item.id) :
[...state.selectedStudents, action.item] // <- no mutation, creates a new array.
}
default:
return state;
}