【发布时间】:2020-11-03 09:31:25
【问题描述】:
我无法遵循这段代码中的设置状态方法。
locked: Array(5).fill(false), ///<<< THIS IS THE INITIAL STATE
this.setState(st => ({ //<<<<< SETTING THE STATE ON BUTTON CLICK
locked: [
...st.locked.slice(0, idx),
!st.locked[idx], // << Iam not able to follow this line and the line after it.
...st.locked.slice(idx + 1)
]
【问题讨论】:
-
反转
locked中位置idx的布尔值。 -
如果写成
this.setState(st => ({ locked: st.locked.map((el, i) => i !== idx ? el : !el)}));可能会更有意义或更容易阅读,当映射索引等于指定索引idx时,它只是切换数组中的布尔值。 -
@Drew Reese 是的,这更容易理解和理解。在我正在学习的课程中,这段代码非常混乱且难以理解。非常感谢。
标签: javascript reactjs slice