[英]ReactJS: Unable to map through array of objects
為什么我無法映射對象數組。 我以前使用過這張地圖,但它似乎在這個組件中不起作用。 知道出了什么問題嗎?
import React, { Component } from "react";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
people: [
{name:"a", age: 21},
{name:"b", age: 22},
{name:"c", age: 23}
]
}
this.clickListnerHandler = this.clickListnerHandler.bind(this)
}
clickListnerHandler(e){
console.log(this.state.people)
}
render(){
return (
<div>
{this.state.people.map((detail, index) =>
{detail.name}
)}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>
)
}
}
export default Home
改變
{this.state.people.map((detail, index) =>
{detail.name}
)}
到
現在有兩種使用 .map 的方法,即使用返回和不返回。 您應該使用 ( 或 { 當您的代碼在 .map 函數中是多行時
無回報
{this.state.people.map(detail=> (
detail.name
))}
有回報
{this.state.people.map(detail=> {
return detail.name
})}
或者,如果它是一行代碼,其中您的.map
返回,那么您不需要返回(
或{
。請查看以下代碼:
{this.state.people.map(detail=> detail.name)}
您在map
回調中使用的語法略有錯誤,這導致地圖函數不返回任何內容。 考慮以下列方式修改您的render()
方法:
render(){
return (<div>
{this.state.people.map((detail, index) => {
// detail.name is returned for each item mapped
return detail.name;
})}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>)
}
或者,您可以使用以下語法,它與上面顯示的內容等效:
render(){
return (<div>
{this.state.people.map((detail, index) => detail.name)}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>)
}
您需要執行傳統的return
或刪除環繞的花括號並執行隱式 return ,其形式為(value) => newvalue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.