【发布时间】:2018-10-17 12:44:43
【问题描述】:
我的方法很简单。它遍历一个对象数组并返回参数中具有给定 id 的对象。这里是:
returnValueToDelete(id) {
this.state.rows.map(function(value) {
if (value["id"] === id) {
console.log(value);
return value;
}
});
}
当我在渲染函数中调用此方法时,实际 id 如下:
console.log(this.returnValueToDelete("IDThatExists"));
它会首先在returnValueToDelete 函数中打印正确的值,因为它被调用,然后打印未定义。谁能解释我为什么以及如何解决这个问题?我在渲染方法中打印了它,因为我想在使用它之前对其进行测试,但它似乎总是会返回undefined,因为我们正在打印返回的内容。非常感谢任何帮助!
编辑
这是我的 this.state.rows:
rows: [
{
id: "name",
numeric: false,
disablePadding: true,
label: "Dessert (100g serving)"
},
{
id: "calories",
numeric: true,
disablePadding: false,
label: "Calories"
},
{
id: "fat",
numeric: true,
disablePadding: false,
label: "Fat (g)"
},
{
id: "carbs",
numeric: true,
disablePadding: false,
label: "Carbs (g)"
},
{
id: "protein",
numeric: true,
disablePadding: false,
label: "Protein (g)"
}
]
【问题讨论】:
-
你的
this.state.rows是什么?还要在else的情况下提供回报。 -
在您的
this.state.rows.map...之前添加一个return -
@Arseniy-II this.state.rows 是一个对象列表,其中一个键是“id”。见编辑
标签: javascript reactjs