Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJS-我不理解此函数中使用的语法_Javascript_Reactjs_Drag And Drop - Fatal编程技术网

Javascript ReactJS-我不理解此函数中使用的语法

Javascript ReactJS-我不理解此函数中使用的语法,javascript,reactjs,drag-and-drop,Javascript,Reactjs,Drag And Drop,我试图理解这个用于react拖放可排序列表的函数 moveCard = (dragIndex, hoverIndex) => { const { cards } = this.state const dragCard = cards[dragIndex] this.setState( update(this.state, { cards: { $splice: [[dragIndex, 1], [hoverIndex

我试图理解这个用于react拖放可排序列表的函数

moveCard = (dragIndex, hoverIndex) => {
    const { cards } = this.state
    const dragCard = cards[dragIndex]

    this.setState(
      update(this.state, {
        cards: {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragCard]],
        },
      }),
    )
}
具体地说,我不懂台词

$splice: [[dragIndex, 1], [hoverIndex, 0, dragCard]],

我试图查找拼接阵列定义,但我不明白这是如何工作的。有人能解释一下吗?

这是一个属性初始值设定项,定义了一个名为$splice的属性,其值为[[dragIndex,1],[hoverIndex,0,dragCard]]

[[dragIndex,1],[hoverIndex,0,dragCard]]是一个数组,包含:

包含dragIndex和1的数组 另一个包含hoverIndex、0和dragCard的数组 $splice属性是一个:

{$splice:array of arrays}对于数组中的每个项,使用该项提供的参数在目标上调用splice

因此,实际上,该代码是这样做的:

const cards = [...this.state.cards];
cards.splice(dragIndex, 1);
cards.splice(hoverIndex, 0, dragCard);
this.setState({cards});
…这意味着它是。基于现有状态设置状态时,必须使用setState的回调版本。我们需要更多的上下文来向您展示如何使用setState的回调版本正确地实现这一点,因为在回调发生时,您不能依赖hoverIndex和dragIndex仍然是正确的。但它看起来是这样的:

// This is GUESSING at several details, such as that the entries in
// `cards` are objects.
const { cards } = this.state;
const cardToRemove = cards[dragIndex];
const addInFrontOf = cards[hoverIndex];
this.setState(prevState => {
    const cards = [...prevState.cards];
    let index = cards.findIndex(cardToRemove);
    if (index != -1) {
        cards.splice(index, 1);
    }
    let index = addInFrontOf ? cards.findIndex(addInFrontOf) : cards.length;
    cards.splice(index, 0, dragCard);
    return {cards};
});
…或使用Immubitibility助手的等效项,但请注意如果dragIndex低于hoverIndex会发生什么

请注意这三行:

const { cards } = this.state;
const cardToRemove = cards[dragIndex];
const addInFrontOf = cards[hoverIndex];
…可能是

const {
    cards: {
      [dragIndex]: cardToRemove,
      [hoverIndex]: addInFrontOf
    }
} = this.state;
……但我认为透明度在那里受到了相当严重的影响-

这是一个问题。对于数组中的每个项,它使用该项提供的参数调用目标上的splice

例如:

const collection = [1, 2, {a: [12, 17, 15]}];
const newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
// Outputs: [1, 2, {a: [12, 13, 14, 15]}]
这将访问集合的索引2,键a,并从索引1开始拼接一个项,以删除17,同时插入13和14