React-native:按日期对数据进行分组并像议程项目一样显示

我想根据日期对数据进行分组并显示日期值及其描述,如下所示。想法是制作像 iPhone 日历一样的议程屏幕。


我的数据将如下所示:


  const events = [

    { date: "2020-04-19", description: "Meeting", startTime: "11:00", endTime: "12:00" },

    { date: "2020-04-19", description: "Coference", startTime: "18:00", endTime: "19:00" },

    { date: "2020-04-20", description: "Team Coference", startTime: "18:00", endTime: "19:00" },

    { date: "2020-04-21", description: "Happy hour cocktail", },

    { date: "2020-04-22", description: "MEditation Class", },

    { date: "2020-04-24", description: "MEditation Class", },

  ]

当前功能:


  function renderEventList() {

  let today = moment().format("YYYY-MM-DD")

  let tomorrow = moment().add(1, 'days').format("YYYY-MM-DD");

   return events.map((d, key) => {

      console.log("data1" , d);

      return ( 

        <View>

          <View>

            <Text>

              {d.date === today ? "Today" : 

              d.date === tomorrow ? "Tomorrow" :

              d.date}

            </Text>

          </View>


          <Text>{d.description}</Text>

        </View>

      )

    })

  }

当前结果:

http://img3.mukewang.com/62c7e2d30001d66002110271.jpg

预期结果(我将管理它的样式部分)

http://img3.mukewang.com/62c7e2dd0001f4fa03770318.jpg


一只甜甜圈
浏览 146回答 1
1回答

慕无忌1623718

我使用您的模拟数据整理了一个 CodeSandbox React 示例。你可以在这里查看。我在那里写了一个函数,groupBy它可能是你正在寻找的。它的功能类似于lodash groupBy 方法,如果您可以将 lodash 添加到项目中,则可以使用该方法。顺便说一句,这是 groupBy 函数的作用:const events = [&nbsp; &nbsp; { date: "2020-04-19", description: "Meeting", startTime: "11:00", endTime: "12:00" },&nbsp; &nbsp; { date: "2020-04-19", description: "Coference", startTime: "18:00", endTime: "19:00" },&nbsp; &nbsp; { date: "2020-04-20", description: "Team Coference", startTime: "18:00", endTime: "19:00" },&nbsp; &nbsp; { date: "2020-04-21", description: "Happy hour cocktail" },&nbsp; &nbsp; { date: "2020-04-22", description: "MEditation Class" },&nbsp; &nbsp; { date: "2020-04-24", description: "MEditation Class" },];const groupBy = (arr, criteria) =>&nbsp; &nbsp; arr.reduce((obj, item) => {&nbsp; &nbsp; &nbsp; &nbsp; let key = typeof criteria === "function" ? criteria(item) : item[criteria];&nbsp; &nbsp; &nbsp; &nbsp; if (!obj.hasOwnProperty(key)) obj[key] = [];&nbsp; &nbsp; &nbsp; &nbsp; obj[key].push(item);&nbsp; &nbsp; &nbsp; &nbsp; return obj;&nbsp; &nbsp; }, {});&nbsp; &nbsp;&nbsp;const grouped = groupBy(events, "date");console.log(grouped);&nbsp; &nbsp;&nbsp;希望这可以帮助,
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript