首页 > 解决方案 > 如何在 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我错误地将数组状态命名为selecteduseState对象的属性相同selected,但它们是无关的。

标签: javascriptreactjsreact-nativeobject

解决方案


您正在直接修改状态,这就是为什么更新不会反映在组件中的原因。为了实现你想要的,你可以使用函数形式setState和对象传播:

 if (selected.includes(markedDay)) {
   setBooking(currentBooking => {
     return {
       ...currentBooking,
       [markedDay]: {
         ...currentBooking[markedDay],
         selected: !currentBooking[markedDay].selected
       }
     }
   })
 }

推荐阅读