kva*_*aaz 5 reactjs react-native redux react-redux
它适用于第一次点击,但是当我再次点击它取消选择它时,它显示了我的错误:
state.selectedStudents.includes 不是函数。(在 'state.selectedStudents.includes(action.item)' 中,'state.selectedStudents.includes' 未定义)
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;
Run Code Online (Sandbox Code Playgroud)
首先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.
}
Run Code Online (Sandbox Code Playgroud)
并且你火了第二次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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8912 次 |
| 最近记录: |