[英]reactjs method keeps returning undefined
我的方法很簡單。 它循環遍歷對象數組,並在參數中返回具有給定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))
我不知道你為什么使用Array.prototype.map()
。
如果您想找到一個match元素,可以使用Array.prototype.find()
,就像這樣
returnValueToDelete(id) {
return this.state.rows.find(e => value["id"] === id);
}
它打印未定義。 誰能解釋為什么以及如何解決這個問題?
因為您忘記了return
語句。
它打印未定義。 誰能解釋為什么以及如何解決這個問題?
您正在正確地創建新數組,但是對結果卻沒有做任何事情。 您可以將其保存到變量,然后將其返回:
const arr = this.state.rows.map(...
...
return arr;
或者直接返回結果:
return this.state.rows.map(...
話雖如此,看來您正在嘗試返回原始數組的一個子集。 因此,您應該使用filter()
而不是map()
:
returnValueToDelete(id) {
this.state.rows.filter(function(value) {
return value["id"] === id
});
}
並使用胖箭頭語法:
returnValueToDelete(id) {
return this.state.rows.filter(value => value["id"] === id);
}
const 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)" } ]; const returnValueToDelete = (id) => { return rows.filter(value => value["id"] === id); } console.log(returnValueToDelete("fat"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.