Cycle.js - 如何获取集合项中的集合长度

Cycle.js - How to get collection length in a collection item

我正在尝试将一些行为专门添加到 Cycle.js 列表中的最后一项。我尝试使用 cycle-onionify 来制作一个像这样的集合:

const List = makeCollection({
  item: Child,
  itemKey: (childState, index) => String(index),
  itemScope: key => key,
  collectSinks: instances => {
    return {
      onion: instances.pickMerge('onion'),
      DOM: instances.pickCombine('DOM')
        .map(itemVNodes => ul(itemVNodes))
    }
  }
});

我知道镜头可用于在组件之间共享状态,但似乎没有办法将镜头与集合一起使用。我想我可以将 Collection 长度传递给 children,这样我就可以将它与 id 进行比较。

有什么我想念的吗?

您可以使用带有 makeCollection 的镜头。请记住,它 returns 是您可以隔离的普通 Cycle.js 组件。所以如果你想添加一个布尔值 isLast 你可以这样做:

function omit(obj, key) {
    let tmp = { ...obj }; //Copy the object first
    delete tmp[key];
    return tmp;
}

const listLens = {
   get: stateArray => stateArray.slice(0, -1).concat({
            ...stateArray[stateArray.length - 1],
            isLast: true
        }),
   set: (stateArray, mappedArray) => mappedArray.slice(0, -1)
           .concat(omit(mappedArray[mappedArray.length - 1], 'isLast'))
};

const List = isolate(
    makeCollection({
        item: Child,
        itemKey: (childState, index) => String(index),
        itemScope: key => key,
        collectSinks: instances => ({
            onion: instances.pickMerge('onion'),
            DOM: instances.pickCombine('DOM')
                .map(itemVNodes => ul(itemVNodes))
        })
    }),
    { onion: listLens, '*': null }
);

附带说明一下,如果您想在每个单独的项目上应用镜头,您也可以这样做,使用 itemScope 属性。例如

itemScope: key => ({ onion: myLens, '*': key })