从数组中删除项目,重新排序项目,然后将其放回(reactjs)

时间:2018-05-14 20:58:37

标签: javascript arrays reactjs

这是我的代码:

reorder = (dragItemId, startIndex, endIndex) => {
        //find the element in the this.state.feladatok which has the same id i pass with reorder
    const dragElem = this.state.feladatok.find(elem => dragItemId === elem.id);
        //find all elements which has the same szid which dragElem has,
        //then sort them. The lista is an array, a piece of this.state.feladatok
    const lista = this.state.feladatok.filter(listaelem => listaelem.szid === dragElem.szid).sort((a, b) => a.rang - b.rang);
      //i need here to remove lista from this.state.feladatok
    const [removed] = lista.splice(startIndex, 1);
    lista.splice(endIndex, 0, removed)
      //now i need to put it back
    fetch('http://localhost:3001/rangvalt', {
        method: 'put',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            lista: lista
        })
    })
    .then(res => res.json())
    .then(ujlista => this.setState({feladatok: ujlista}))
      //because waiting for this response is too slow
    .catch(err => console.log(err)) ;
    }

这是我在反应中使用的功能,并且运行良好,但是等待服务器的响应会导致UX问题,我可以(我认为)轻松解决不只是更新服务器端,而是立即在客户端更新。这里的主要问题是删除。那么如何将lista的方法扩展为不只是获取和排序,而是使用setState()(或其他内容)删除它们?

1 个答案:

答案 0 :(得分:0)

这是将元素添加到endIndex的方法。除非我误解了这个问题,否则你不应该startIndex

const dragElem = this.state.feladatok.find(elem => dragItemId === elem.id);
// Remove dragElem from array
const lista = this.state.feladatok.filter(listaelem => listaelem.szid === dragElem.szid).sort((a, b) => a.rang - b.rang);

// Insert dragElem into lista at index endIndex
const newLista = [...lista.slice(0, endIndex), dragElem, ...lista.slice(endIndex)];
this.setState({feladatok: newLista});