gpt4 book ai didi

javascript - 如何连接对象是useState数组?

转载 作者:行者123 更新时间:2023-12-05 03:40:15 24 4
gpt4 key购买 nike

我有 useState 变量。我想用新对象连接值。

const [dates,setDates] = useState(["Mon","Sun"])

规则:1.如果日期存在带有 isSelected 标志则设为 false

[{day:"mon",isSelected:false}]

否则,做为,

[{day:"mon",isSelected:true}]

下面是我的函数,

const handleDay = (day) => {
setDates((x) => {
x.map((v) => {
if (day === v.day && v.isSelected) {
v.isSelected = true;
return {
v,
};
} else {
return {
day,
isSelected: true,
};
}
});
});
};

handleDay('mon');

预期输出

[{day:"mon",isSelected:true}, 'Sun']

但是我明白了,

 [{
"day": "Mon",
"isSelected": true
}, {
"day": "Mon",
"isSelected": true
}]

最佳答案

用这个替换你的 map 代码

arr.map(v => {
if (day === v.day || day === v) {
return {
day: v.day ? v.day : v,
isSelected: !v.isSelected
};
} else {
return v
}
});

let arr = ["Mon", "Sun"]

const handleDay = day => {
let arr2 =
arr.map(v => {
if (day === v.day || day === v) {
return {
day: v.day ? v.day : v,
isSelected: !v.isSelected
};
} else {
return v
}
});

return arr2;
};

console.log(handleDay('Mon'));
arr = handleDay('Mon');
console.log(handleDay('Mon'));

关于javascript - 如何连接对象是useState数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68254444/

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