它适用于第一次单击,但是当我再次单击它以取消选择它时,它显示错误:
state.selectedStudents.includes is not a function. (In 'state.selectedStudents.includes(action.item)', 'state.selectedStudents.includes' is undefined)
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() return value: The new
length
property of the object upon which the method was called.
所以在第一个
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;
}
关于reactjs - array.includes() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57755599/