gpt4 book ai didi

arrays - Redux reducer ,检查状态数组中是否存在值并更新状态

转载 作者:行者123 更新时间:2023-12-03 13:39:36 24 4
gpt4 key购买 nike

所以我有一个数组chosenIds[],它本质上包含一个ids(数字)列表。但我无法访问化简器中的状态来检查我解析到操作的 ID 是否在数组中。

  const initialState = {
'shouldReload': false,
'chosenIds': [],
};

export default function filter(state = initialState, action) {
switch (action.type) {


case ADD_TYPE:
console.log(state.chosenIds, "Returns undefined???!!!");

// Check if NUMBER parsed is in state
let i = state.chosenIds.indexOf(action.chosenId);

//If in state then remove it
if(i) {
state.chosenIds.splice(i, 1);
return {
...state.chosenIds,
...state.chosenIds
}
}
// If number not in state then add it
else {
state.chosenIds.push(action.chosenId)
return { ...state.chosenIds, ...state.chosenIds }
}

我不确定发生了什么...但是当我记录 state.chosenIds 时,它返回 undefined?它甚至不返回初始的空数组 []

基本上,此函数的作用是检查 action.chosenId 是否在 state.chosenIds 中,如果是,则删除 >action.chosenId 值,如果不是,则将 action.chosenId 添加到状态。

最佳答案

我在这里看到了一些不同的问题。

首先,您对已处于该状态的数组使用 splice()push()。这是直接突变,它会破坏 Redux。您需要制作该数组的副本,然后修改该副本。

其次,对象传播的用法看起来不正确。您使用它时就好像“chosenIds”是一个对象,但它是一个数组。此外,您还复制了价差。这导致返回的状态不再具有名为“chosenIds”的字段。

第三,如果没有找到,Array.indexOf() 返回 -1,这实际上算作“true”,因为它不是 0。因此,当前的 if/else 不会按照您的预期执行。

我会重写你的 reducer ,如下所示:

export default function reducer(state = initialState, action) {
switch(action.type) {
case ADD_TYPE:
let idAlreadyExists = state.chosenIds.indexOf(action.chosenId) > -1;
// make a copy of the existing array
let chosenIds = state.chosenIds.slice();

if(idAlreadyExists) {
chosenIds = chosenIds.filter(id => id != action.chosenId);
}
else {
// modify the COPY, not the original
chosenIds.push(action.chosenId);
}

return {
// "spread" the original state object
...state,
// but replace the "chosenIds" field
chosenIds
};
default:
return state;
}
}

关于arrays - Redux reducer ,检查状态数组中是否存在值并更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35789221/

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