它适用于第一次点击,但是当我再次单击它以取消选择它时,它向我显示错误:
state.selectedStudents.include 不是一个函数。(在 'state.selectedStudents.include(action.item(', "state.selectedStudents.include"未定义(
import {
SELECT
} from "../actions/postActionTypes";
const initialState = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: []
}
const selectReducer = (state = initialState, action) => {
switch (action.type) {
case SELECT:
return {
...state,
selectedStudents: state.selectedStudents.includes(action.item) ? state.selectedStudents.splice(state.selectedStudents.indexOf(action.item), 1) : state.selectedStudents.push(action.item)
}
default:
return state;
}
}
export default selectReducer;
首先,state.selectedStudents.includes is not a function.
意味着state.selectedStudents
不是一个数组。 那是什么呢?
.push()
不返回数组,而是返回推送后数组的长度。 基于 MDN:
Array.push(( 返回值:调用该方法的对象的新
length
属性。
因此,在第一个SELECT
操作之后,您的状态会变成这样:
state = {
students: ['Aditya', 'Rohan', 'Hello'],
selectedStudents: 1, // <- it's a number, not an array.
}
第二次触发SELECT
动作时,state.selectedStudents.includes(action.item)
抛出和错误,因为state.selectedStudents
1
不是数组。
将开关大小写更改为:
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;
}
state.selectedStudents.push(action.item)
返回数组的新长度,而不是列表。 因此,下次尝试时,类型号没有 Include 方法。
你直接改变了你的状态。代替splice
和push
使用filter
数组扩展运算符:
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;
}
在任何情况下,我都不会鼓励改变 redux 状态。所以这是我的建议
const selectReducer = (state = initialState, action) => {
switch (action.type) {
case SELECT: {
let selectedStudents = [...state.selectedStudents];
if (!_.isEmpty(selectedStudents) && selectedStudents.includes(action.item)) {
const itemIndex = selectedStudents.indexOf(action.item);
selectedStudents = selectedStudents.splice(itemIndex, 1);
} else {
selectedStudents.push(action.item);
}
return {
...state,
selectedStudents,
};
}
default:
return state;
}
};