reactjs - array.includes() 不是函数

标签 reactjs react-native redux react-redux

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

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/

相关文章:

reactjs - mapStateToProps 中的状态是 JSX! react /还原

javascript - 限制 Reducer 的结果

reactjs - 如何在 Next.js 中设置全局上下文而不会出现 "Text content did not match"错误?

reactjs - 如何在react js中获取带问号的url参数?

reactjs - enzyme :用浅层,redux store更新不会触发componentDidUpdate

reactjs - 使用 Async/Await 进行 native 调试

javascript - React Redux 使用连接组件的 HOC

node.js - 有关如何为聊天应用程序设计良好架构的建议?

javascript - 在 reducer 中向 redux store 添加功能是一种反模式?

javascript - Firebase连接到集合,但按键过滤