使用 Cycle.js,我尝试创建一个 View ,在给定一组数据点时呈现动态数量的组件。但是,我不知道如何创建重复 View 。
我已经将所有内容都剥离回最基本的示例,我认为它应该如何工作。希望有人能指出我所缺少的东西。
/*
Expected:
Given an array of data objects, create the following DOM
<div class="container">
<h1 class=".data">Element 1</h1>
<h1 class=".data">Element 2</h1>
<h1 class=".data">Element 3</h1>
<h1 class=".data">Element 4</h1>
...
</div>
Result:
<div class="container">
<h1 class=".data">Element 9</h1>
</div>
*/
function view( data$ ){
return Rx.Observable.of(
div('.container', data$.map( data =>
h1('.data', `Element: ${ data.id }`)
))
);
}
function main( sources ) {
// Create an array of objects
const arr = [];
for( let i = 0; i < 10; i++ ){
arr.push({
id: `id ${i}`
})
}
// Convert array to an observable
const data$ = Rx.Observable.from(arr);
const vtree$ = view( data$ );
return {
DOM: vtree$
};
}
const drivers = {
DOM: CycleDOM.makeDOMDriver('#mountPoint')
};
Cycle.run( main, drivers );
最佳答案
你的数组有 10 个项目,因此 observable 将发出 10 个项目。可观察量代表随时间变化的数据。所以你的可观察值代表了 10 个时间点。其中仅使用最新的。这就是为什么您只看到“元素 9”。
您可能希望创建一个仅包含一项的可观察对象,而不是将数组转换为可观察对象:您的数组。
将Rx.Observable.from(arr)
更改为Rx.Observable.just(arr)
下一期是你的 View 函数:
function view( data$ ){
return Rx.Observable.of(
div('.container', data$.map( data =>
h1('.data', `Element: ${ data.id }`)
))
);
}
您的 View 函数采用 data$
参数。将data$
读取为数据流
或数据流
。所以你的函数接受一个流
到目前为止这是正确的。
但是现在您正在通过 Observable.of
创建一个新的 Observable。那不是你想做的。相反,您可能只想将 data$
(即数据流)转换为虚拟 DOM 节点流:
function view( data$ ){
return data$.map( data =>
// here you should return a virtual DOM node
)
}
请记住:data$
是您一段时间内的数据。对于每个时间点,您都有一些数据。对于每个时间点,您都希望拥有一些 DOM 树。
function view( data$ ){
return data$.map( data =>
div('.container',
// data is not a single of your items but the whole array of items
// hence we can map over it and transform each item into a child nod:
data.map((item) => div('.item', item.id))
)
)
}
注意:data$.map
与 data.map 有很大不同。第一个转换/映射一个可观察的,后面一个转换/映射一个经典数组。
奖金:
for( let i = 0; i < 10; i++ ){
arr.push({
id: `id ${i}`
})
}
您正在以程序方式创建数组。您可能更喜欢创建大小为 10 的数组并将其转换为包含您的项目的数组的函数式方法:
Array.apply(Array, {length: 10}).map(
(_,index) => ({id: `id: ${index}`})
)
关于javascript - 如何使用 Cycle.js 创建动态的重复元素列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116972/