如何在React中修改对象属性

时间:2019-11-13 19:13:22

标签: javascript reactjs react-native object

我有一个采用以下形式的对象:

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

P.S。我错误地将selected的数组状态useState命名为对象selected的属性,但是它们是不相关的。

1 个答案:

答案 0 :(得分:3)

您正在直接修改状态,这就是为什么更新未反映在组件中的原因。要实现所需的功能,可以使用setState和对象散布的功能形式:

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