繁体   English   中英

如何获得下一个和上一个项目?

[英]How to get next and previous item?

如何获得下一个项目,上一个项目? 例如,第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]
            );
    }

这是您可以迭代项目的方式:

  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()); 
根据您的要求(第3到第5),您需要在切换之前添加一些检查。 我猜(由于问题尚不清楚),您想要NEXT DATE项,但是我提供的代码应允许您自己非常接近该日期。

PS:您还应该考虑到达FIRST / LAST项目时会发生什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM