【问题标题】:Order documents in firestore based on their drag and drop position根据拖放位置在 Firestore 中对文档进行排序
【发布时间】:2020-12-06 16:59:14
【问题描述】:

我的目标是渲染我的 LinkContainer 组件,以便它们在我的拖放上下文中:

<DragDropContext onDragEnd={handleOnDragEnd}>
          <Droppable droppableId="characters">
            {(provided) => (
              <ul
                className="characters"
                {...provided.droppableProps}
                ref={provided.innerRef}
              >
                {links.map((l, index) => {
                  return (
                    <Draggable key={l.id} draggableId={l.id} index={index}>
                      {(provided) => (
                        <li
                          className="draggable"
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          ref={provided.innerRef}
                        >
                          <LinkContainer
                            linkTitle={l.linkTitle}
                          />
                        </li>
                      )}
                    </Draggable>
                  );
                })}
              </ul>
            )}
          </Droppable>
        </DragDropContext>

这是允许我拖放同时将links设置为新顺序的功能:

 const reorder = (links, startIndex, endIndex) => {
    const result = Array.from(links);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);

    return result;
  };

  // handle drag end
  const handleOnDragEnd = (result) => {
    console.log(result);
    setLinks(reorder(links, result.source.index, result.destination.index));
  };

如何更新我的 firebase 记录,以便在重新加载页面上通过 links 映射时,LinkContainer 以最后的顺序呈现?

我是否必须在文档本身上创建一个索引并使用LinkContainer 的位置更新它

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    根据您添加属性以将其用作索引的建议,我想分享以下意见:

    例如,使用这种方法,您需要更新列表中的所有元素,以便在数据库中重新创建新订单,每次移动对象时都会执行此操作。

    如果这是一个小集合,这会起作用,但如果您的集合有很多对象,或者如果您经常移动对象,这将转化为大量的读写操作。

    在最坏的情况下

    (documents in collection) * (# of movements)
    

    另一种选择是创建一个具有所需顺序的数组(数组在他的顺序上总是静态的),例如这是集合中对象的默认状态

    ["1a","1c","2b","3x"]
    

    但是在前端的动作之后,它看起来像这样

    ["1a","2b","3x","1c"]
    

    可以将前端的状态存储在一个单独的集合中的一个文档内的一个数组中,以便不修改原始对象并避免在每次移动中重新更新所有元素,但这将继续受到影响用户在前端执行的移动数量,并且您需要根据集合上文档的创建或删除来更新数组。

    您必须按照数组顺序以所需的方式显示您的信息。

    最后一种选择,也许效率较低,每次移动发生时都重写整个集合(使用前端快照),重写集合算作一次写入操作,但这可能会在未来产生并发操作的问题。

    【讨论】:

    • 这太棒了!谢谢!
    猜你喜欢
    • 2012-03-21
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多