简体   繁体   English

在React中通过Map循环

[英]Looping through a Map in React

I have a Map object: 我有一个Map对象:

let dateJobMap = new Map();

for (let jobInArray of this.state.jobs) {
  let deliveryDate: Date = new Date(jobInArray.DeliveryDate);
  let deliveryDateString: string = deliveryDate.toLocaleDateString("en-US");

  if (dateJobMap.has(deliveryDateString)) {
    let jobsForDate: IDeliveryJob[] = dateJobMap.get(deliveryDateString);
    jobsForDate.push(jobInArray);
  }
  else {
    let jobsForDate: IDeliveryJob[] = [jobInArray];
    dateJobMap.set(deliveryDateString, jobsForDate);
  }
}

In my render method, I want to call a TruckJobComp object for each delivery job in the value's array to display it: 在我的render方法中,我想为值的数组中的每个传递作业调用一个TruckJobComp对象来显示它:

        <div className={ styles.column }>
          <p className={ styles.description }>{escape(this.props.description)}</p>

          {
            dateJobMap.forEach(function(jobsForDate, dateString) {
              jobsForDate.map(job => (
                <TruckJobComp job = { job } />
              ))
            })
          }
        </div>

This seems like it should work but doesn't. 这似乎应该有效,但不是。 It never creates a TruckJobComp. 它永远不会创建TruckJobComp。 I do a .forEach iteration on my Map , and for each value 's array , I use .map to get the individual job object to send to TruckJobComp object. 我在Map上执行.forEach迭代,对于每个valuearray ,我使用.map来获取要发送到TruckJobComp对象的单个作业对象。

When I create a temp array to grab the jobs from the last loop: 当我创建一个临时array来从最后一个循环中获取作业时:

let tempJobs: IDeliveryJob[];

and in the loop add in: 并在循环中添加:

  if (dateJobMap.has(deliveryDateString)) {
    let jobsForDate: IDeliveryJob[] = dateJobMap.get(deliveryDateString);
    jobsForDate.push(jobInArray);

    tempJobs = jobsForDate;
  }

and then use that array in the render: 然后在渲染中使用该array

          <div className={ styles.column }>
            <p className={ styles.description }>{escape(this.props.description)}</p>
            {
              tempJobs.map(job => (
                <TruckJobComp job = { job }/>
              ))
            }
          </div>

It displays as expected. 它按预期显示。

I do have a warnings in Visual Studio Code: 我在Visual Studio代码中有警告:

Warning - tslint - ...\TruckDeliverySchedule.tsx(104,38): error no-function-expression: Use arrow function instead of function expression

I don't know enough to understand. 我不太了解。 Line 104 corresponds with: 第104行对应于:

dateJobMap.forEach(function(jobsForDate, dateString) {

I am very new to this so I'm not 100% sure how most of this works. 我对此非常陌生,所以我不能100%确定大部分工作原理。 Just trying to put pieces I've learned together to get things to work. 只是想把我学到的东西放在一起,让事情发挥作用。

Second Edit: 第二编辑:

{escape(this.props.description)} {逃逸(this.props.description)}

{
  [...dateJobMap.keys()].map(jobsForDate => // line 154
    jobsForDate.map(job => (
      <TruckJobComp job = { job } />
    ))
  )
}

Produces error: 产生错误:

[09:06:56] Error - typescript - src\...\TruckDeliverySchedule.tsx(154,27): error TS2461: Type 'IterableIterator<any>' is not an array type.

dateJobMap.forEach(...) returns undefined , so it cannot be mapped to a collection of elements. dateJobMap.forEach(...)返回undefined ,因此无法映射到元素集合。

ES6 maps have forEach method for compatibility purposes (generally for..of is preferred to iterate over iterables) and don't have map method. ES6图具有forEach为了兼容性的方法(通常for..of优选遍历iterables)和不具有map的方法。 A map should be converted to array first, then it could be mapped to an element. 应首先将地图转换为数组,然后将其映射到元素。 Since values aren't used, only keys need to be retrieved: 由于未使用值,因此只需要检索密钥:

  {
    [...dateJobMap.keys()].map(jobsForDate =>
      jobsForDate.map(job => (
        <TruckJobComp job = { job } />
      ))
    )
  }

All this warning is saying is that instead of using the syntax function(jobsForDate, dateString) {} you should use the syntax (jobsForDate, dateString) => {} . 所有这些警告都说不是使用语法function(jobsForDate, dateString) {}而是使用语法(jobsForDate, dateString) => {}

The reason could be the way this is scoped in arrow functions versus function expressions. 究其原因可能是这样this在箭头功能与函数表达式作用域。 See this post. 这篇文章。

My guess as to the reason your first approach didn't work but your second one did is that forEach doesn't actually return an array, and if it did, calling map within forEach would return an array of arrays (but, again, it doesn't). 我猜你的第一个方法不起作用的原因,但你的第二个方法确实是forEach实际上没有返回一个数组,如果确实如此,在forEach调用map将返回一个数组数组(但是,同样,它没有)。 Not sure how React would handle that, but React does know how to handle a single array, which is what your last approach returns. 不确定React将如何处理,但React确实知道如何处理单个数组,这是你的最后一个方法返回的。

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

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