如何获取下一个项目,上一个项目?例如,第3个活动项,当我单击下一个按钮时,该函数返回第5个项。
我的JSON数据:
const DataJ = [
{ date: '2018-05-17T15:11:23.351Z'},
{ date: '2018-01-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-12-17T15:11:23.351Z'}
];
上一个和下一个功能。
const nextItem = () => {
// Next json item
console.log();
}
const prevItem = () => {
// Prev json item
console.log();
}
<div>
<button type="button" className="control-btn" onClick="prevItem"> Prev </button>
<button type="button" className="control-btn" onClick="nextItem"> Next </button>
</div>
我尝试使用此方法:
const prevItem = () => {
const { DataJ } = this.props;
const curDate = new Date(Date.now());
console.log(DataJ[0]);
return DataJ.reduce(
(a, b) =>
new Date(b.date) <= curDate
? b : a,
DataJ[0]
);
}
答案 0 :(得分:0)
这是您可以迭代项目的方式:
var myApp = window.MyApp || {};
const DataJ = [
{ date: '2018-05-17T15:11:23.351Z'},
{ date: '2018-01-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-10-17T15:11:23.351Z'},
{ date: '2018-12-17T15:11:23.351Z'}
];
myApp.currentIndex = 0;
myApp.currentItem = function () {
return DataJ[myApp.currentIndex];
};
myApp.prevItem = function () {
myApp.currentIndex--;
return myApp.currentItem();
};
myApp.nextItem = function () {
myApp.currentIndex++;
return myApp.currentItem();
};
console.log(myApp.currentItem());
console.log(myApp.nextItem());
console.log(myApp.nextItem());
console.log(myApp.prevItem());
P.S。 您还应该考虑到达FIRST / LAST项目时会发生什么。