gpt4 book ai didi

reactjs - array.includes() 不是函数

转载 作者:行者123 更新时间:2023-12-04 12:18:22 24 4
gpt4 key购买 nike

它适用于第一次单击,但是当我再次单击它以取消选择它时,它显示错误:

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.selectedStudents1这不是一个数组。

将您的开关盒更改为:
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com