我的方法很简单。它循环遍历对象数组,并在参数中返回具有给定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
函数中打印正确的值,但随后会打印未定义的值。谁能解释为什么以及如何解决这个问题?我在render方法中打印了它,因为我想在使用它之前先对其进行测试,但是由于我们正在打印返回的内容,因此它似乎总是返回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: [
{id:1, name: 'ss'},
{id:2, name: 'aa'}
]
};
returnValueToDelete(id) {
return this.state.rows.filter(value => value.id === id)
}
console.log(this.returnValueToDelete(1))