我无法遵循这段代码中的set state方法。
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)
]
答案 0 :(得分:1)
它只是抵消了idx
位置上的项目。
它是如何做到的?
首先,它从idx
复制locked
之前的所有元素,并将其粘贴回locked
内的下一行。
this.setState(st => ({
locked: [ ...st.locked.slice(0, idx)]
}));
然后它否定了idx
位置上的项目。
!st.locked[idx]
然后将其余项目复制回数组中。
...st.locked.slice(idx + 1)
答案 1 :(得分:1)
locked
是一个布尔数组。此代码利用传播语法从当前的布尔数组创建一个新的布尔数组,但idx
处的一个元素反转了。详细明细:
this.setState(st => ({ // callback version of setState that receives the current state as the argument
locked: [ // set a new array for `locked` that consists of :
...st.locked.slice(0, idx), // every element before the element at idx
!st.locked[idx], // the element at idx but inverted
...st.locked.slice(idx + 1) // every element after idx
]
您还可以创建原始数组的副本,然后在idx
处反转元素:
this.setState(st => {
const locked = Array.from(st.locked);
locked[idx] = !locked[idx];
return {locked};
});
或者您可以在数组上进行映射:
this.setState(st => ({
locked: st.locked.map((item, i) => i === idx ? !item : item)
}));
所有这些解决了在创建新数组时反转idx
处的元素的问题(反应状态不得突变)。
答案 2 :(得分:1)
//locked is a state property with an array value of 5 false booleans
locked: Array(5).fill(false)
//passing current state through a function
this.setState(st => ({
//selecting locked property of state to update
locked: [
//making a copy of all indexes up to the index that is to be updated
...st.locked.slice(0, idx),
//toggling the selected index to have a value of true (if previously false)
!st.locked[idx],
//making a copy of all indexes after the index that is to be updated
...st.locked.slice(idx + 1)
]
}))
答案 3 :(得分:0)
如果不了解idx
的来源,这是不完整的。但是它会将st.locked
数组中的所有内容都保留下来,并且保留不变,除了idx
会反转。
然后,它会返回带有这些元素的 new数组,这些元素必须是故意进行的。否则,将st.locked [idx]作为目标将是微不足道的。 出于某些原因,这段代码的作者返回了一个新数组,这可能很重要。
答案 4 :(得分:0)
您好,我在这段代码上进行了尝试,现在我很清楚了。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(0, 2));
console.log(animals[2] = "New Item Bro")
console.log(animals.slice(2 + 1));
console.log(animals)