英文:
Why is the .map() function not iterating?
问题
我试图通过.map()迭代我的状态,但函数在第一个返回后停止:
private renderEmployeesTable() {
if (this.state.employees) {
return new Array(this.state.employees).map((_, index) => {
const employeeId: string | undefined = this.state.employees[index]?.employeeId;
const employeeName: string | null = this.state.employees[index]?.name;
return (
<>
<div className="row">
<div className="col">
<p className="rowText">{employeeId}</p>
</div>
<div className="col">
<p className="rowText">{employeeName}</p>
</div>
<div className="col">
<p className="rowText">
{this.state.workingHoursForEveryEmployee.find(
(res) => res.employeeId === employeeId
)?.workingHours}
</p>
</div>
<div className="col">
<p className="rowText">{this.state.hoursToWork}</p>
</div>
</div>{" "}
</>
);
});
}
}
在控制台中,索引为0且不递增。 你有任何想法,我如何修复这个问题?
英文:
I am trying to iterate through my state via .map(), but the function stops after the first return:
private renderEmployeesTable() {
if (this.state.employees) {
return new Array(this.state.employees).map((_, index) => {
const employeeId: string | undefined =
this.state.employees[index]?.employeeId;
const employeeName: string | null = this.state.employees[index]?.name;
return (
<>
<div className="row">
<div className="col">
<p className="rowText">{employeeId}</p>
</div>
<div className="col">
<p className="rowText">{employeeName}</p>
</div>
<div className="col">
<p className="rowText">
{
this.state.workingHoursForEveryEmployee.find(
(res) => res.employeeId === employeeId
)?.workingHours
}
</p>
</div>
<div className="col">
<p className="rowText">{this.state.hoursToWork}</p>
</div>
</div>{" "}
</>
);
});
}
}
In the console, index is 0 and doesn't go up.
Do you have any idea, how I could fix this?
答案1
得分: 2
你正在创建一个新的Array()
,其中只包含1个项目:一个数组。
你可能不需要new Array()
部分,直接映射this.state.employees
即可。
英文:
Your are creating a new Array()
which contains only 1 item: an array.
You probably don't need the new Array()
part, just map this.state.employees
directly.
答案2
得分: 0
你正在尝试创建一个仅具有this.state.employees
作为元素的数组。如果你想要使用this.state.employees
中的元素进行迭代,直接使用map
函数。如果想要创建类似数组的可迭代对象,请使用Array.from()
。
英文:
You are trying to create an array that has only this.state.employees
as an element. If you want to iterate elements with map in this.state.employees
, use the map function directly.
If you want to create iterables in the form of an Array, use Array.from()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论