[英]Can't understand filter and findIndex in the following code? in react-redux reducer function
在这段代码中
**reducers: {
addDiary(state, { payload }: PayloadAction<Diary[]>) {
const diariesToSave = payload.filter((diary) => {
return state.findIndex((item) => item.id === diary.id) === -1;
});
state.push(...diariesToSave);
},**
state.findIndex((item)=>item.id === diary.id) 正在返回索引号,但是当我们在过滤器中使它等于 -1 时,它将始终为 false,因为索引从 0 开始。那么如何我们把日记推到了状态? 我是新手,从以下文章中学习 redux: https : //www.smashingmagazine.com/2020/08/redux-real-world-application/
我所指的代码几乎在文章中间
findIndex
方法要么返回满足条件item.id === diary.id
的项目的索引,要么返回 -1,以防条件永远不成立。
并且代码中的filter
方法只会返回那些满足以下条件的项目: state.findIndex((item) => item.id === diary.id) === -1;
因此,如果findIndex
返回 0, filter
方法不会将该项目添加到diariesToSave
数组,因为 0 不等于 -1。 只有那些项目会被添加到diariesToSave
数组,其中findIndex
方法将返回 -1。
希望能消除你的困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.