[英]ReactJS: Unable to map through array of objects
Why am I not able to map through array of objects.为什么我无法映射对象数组。 I have used this map before but it doesn't seem to be working in this component.
我以前使用过这张地图,但它似乎在这个组件中不起作用。 Any idea what is wrong?
知道出了什么问题吗?
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
Change改变
{this.state.people.map((detail, index) =>
{detail.name}
)}
To到
these days there are two ways to use .map ie, by using return and without return.现在有两种使用 .map 的方法,即使用返回和不返回。 You should use ( or { when your code is multi line inside .map function
您应该使用 ( 或 { 当您的代码在 .map 函数中是多行时
Without return无回报
{this.state.people.map(detail=> (
detail.name
))}
With return有回报
{this.state.people.map(detail=> {
return detail.name
})}
Or if it is a single line of code, in which your .map
returns, then you don't need to return (
or {
. Please take a look at the below code:或者,如果它是一行代码,其中您的
.map
返回,那么您不需要返回(
或{
。请查看以下代码:
{this.state.people.map(detail=> detail.name)}
Your use of syntax in the map
callback is slightly incorrect, which is causing the map function to not return anything.您在
map
回调中使用的语法略有错误,这导致地图函数不返回任何内容。 Consider revising your render()
method in the following way:考虑以下列方式修改您的
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>)
}
Alternatively, you can use the following syntax which is shorthand equivalent to what is shown above:或者,您可以使用以下语法,它与上面显示的内容等效:
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.