簡體   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