[英]Error while iterating over array elements
我有以下數組 -
var arr= [
{
id:1,
name:"some name 1",
email:"somename1@email.com"
},
{
id:2,
name:"some name 2",
email:"somename2@email.com"
}
]
我想以一種方式迭代,我希望 output 作為字符串(半列分隔的名稱字符串)-
"some name 1;some name 2"
我以下面的方式迭代它 -
var name="";
arr.forEach( (item:any)=> {
name+=item.name+";";
});
但是我遇到了以下錯誤-
UncoughtError : Objects are not valid as react child (found object with keys {id , name , email}). If you want to render collection of child use array instead.
編輯:
return (
<span> {name} </span>
)
實現所需內容的一種簡單方法是使用Array.prototype.reduce()
您可以使用 ES6 嘗試以下代碼:
const arr= [ { id:1, name:"some name 1", email:"somename1@email.com" }, { id:2, name:"some name 2", email:"somename2@email.com" } ] const newString = arr.reduce((preVal, newVal) => `${preVal} ${preVal? ";": ""} ${newVal.name} `, "") console.log(newString)
該錯誤通常意味着您正在嘗試渲染不直接是 React 組件的東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.