React-dnd $splice 做什么
React-dnd what does $splice do
我正在阅读an example of the React-dnd project:
moveCard(dragIndex, hoverIndex) {
const { cards } = this.state;
const dragCard = cards[dragIndex];
this.setState(update(this.state, {
cards: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
}
}));}
这个$splice和on this page解释的一样吗?
谁能解释一下这段代码的作用? $splice
函数让我很困惑。
它基本上是普通拼接函数的不可变版本,例如
newcards.splice(dragIndex, 1); // removing what you are dragging.
newcards.splice(hoverIndex, 0, dragCard); // inserting it into hoverIndex.
这些不变性助手不是直接操作目标数组,而是通过创建和分配新状态来帮助您更新状态。
我花了一段时间才明白。这是传统箭头函数的逐步解释
moveCard = (dragIndex, hoverIndex) => {
// list of cards
let newcards = this.state.cards;
// dragCard is card we are dragging
let dragCard = newcards[dragIndex];
// removing this dragCard from array
newcards.splice(dragIndex, 1);
// insert dragCard at hover position
newcards.splice(hoverIndex, 0, dragCard);
// update State
this.setState({
cards: newcards
});
};
我正在阅读an example of the React-dnd project:
moveCard(dragIndex, hoverIndex) {
const { cards } = this.state;
const dragCard = cards[dragIndex];
this.setState(update(this.state, {
cards: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
}
}));}
这个$splice和on this page解释的一样吗?
谁能解释一下这段代码的作用? $splice
函数让我很困惑。
它基本上是普通拼接函数的不可变版本,例如
newcards.splice(dragIndex, 1); // removing what you are dragging.
newcards.splice(hoverIndex, 0, dragCard); // inserting it into hoverIndex.
这些不变性助手不是直接操作目标数组,而是通过创建和分配新状态来帮助您更新状态。
我花了一段时间才明白。这是传统箭头函数的逐步解释
moveCard = (dragIndex, hoverIndex) => {
// list of cards
let newcards = this.state.cards;
// dragCard is card we are dragging
let dragCard = newcards[dragIndex];
// removing this dragCard from array
newcards.splice(dragIndex, 1);
// insert dragCard at hover position
newcards.splice(hoverIndex, 0, dragCard);
// update State
this.setState({
cards: newcards
});
};