javascript - 如何在 React 中修改对象属性
问题描述
我有一个采用以下形式的对象:
booking Object {
"2019-11-29": Object {
"selected": true,
},
"2019-11-30": Object {
"selected": true,
},
}
我想通过调用函数来修改。更具体地说,我想切换selected
属性,即布尔值。
我想调用一个函数,1)检查对象中是否存在某个键,在本例中为“2019-11-29”,如果存在,2)切换selected
属性,而对象中的其他所有内容都保留相同。
我的以下代码临时切换selected
属性,但不会将其保存在状态中。
const [selected, setSelected] = useState([])
const [booking, setBooking] = useState({})
const select = day => {
let markedDay = day.dateString
// first checks in the "selected" array to see if the "markedDay" exists
if(selected.includes(markedDay)){
// toggles the property within the "booking" object
booking[markedDay] = {
selected: !booking[markedDay].selected
}
setBooking(booking) // this hook doesn't update the state with the newly toggled object property
}
// saves the "markedDay" into a new array if it doesn't exist in the array already
const newSelected = [...selected, markedDay];
// assigns the property "selected" to the newly entered date and combines it with the pre-existing object
let obj = newSelected.reduce((c, v) => Object.assign(c, {
[v]: {
selected: true,
}
}), {})
setSelected(newSelected)
setBooking(obj);
}
我暂时的意思是,当我在切换booking
后立即控制台记录对象时booking[markedDay].selected
,它会显示属性显示为false
,这是预期的结果。booking
但是,如果我要在语句之外控制日志if
,则全局状态仍将属性显示为true
.
PS我错误地将数组状态命名为selected
与useState
对象的属性相同selected
,但它们是无关的。
解决方案
您正在直接修改状态,这就是为什么更新不会反映在组件中的原因。为了实现你想要的,你可以使用函数形式setState
和对象传播:
if (selected.includes(markedDay)) {
setBooking(currentBooking => {
return {
...currentBooking,
[markedDay]: {
...currentBooking[markedDay],
selected: !currentBooking[markedDay].selected
}
}
})
}
推荐阅读
- google-cloud-firestore - 是否有一种简单的方法可以将文档字段值复制到同一文档中的另一个新字段以用于整个 Firestore 集合
- swift - 在 Swift 中,有没有办法知道文件是否正在下载?
- excel - Excel 将循环结果输出到带有循环的每一行的新单元格
- python - DictReader 应该在错误的列数上出错
- json - 如何在 Postgres 的 JSONB 字段中编辑 JSON 对象深处的单个值?
- python - 通过比较两个字典的值来创建第三个字典
- php - 来自 php 文件的奇怪语法
- blazor - 如何在 Blazor WebAssembly 中实现外部异步操作完成?
- c# - ASP.Net Core 为我的应用程序处理了太多 cookie
- r - R 3.6.2 - SDMTools 不可用