ReactJS:无法通过对象数组进行映射

时间:2018-12-25 03:15:21

标签: javascript reactjs

为什么我不能通过对象数组进行映射。我以前曾使用过此地图,但在此组件中似乎无法使用。知道有什么问题吗?

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

3 个答案:

答案 0 :(得分:3)

更改

   {this.state.people.map((detail, index) => 
          {detail.name}
       )}

收件人

这几天,有两种使用.map的方法,即使用return和不使用return。您应该使用(或{当您的代码在.map函数中为多行时

没有回报

  {this.state.people.map(detail=> (
           detail.name
       ))}

有回报

   {this.state.people.map(detail=> {
           return detail.name
       })}

或者,如果.map返回的是单行代码,则无需返回和(或{。请查看下面的代码

    {this.state.people.map(detail=> detail.name)}

答案 1 :(得分:1)

您在map回调中使用的语法略有错误,这导致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>)
    }

答案 2 :(得分:1)

您需要执行传统的return或删除环绕的花括号并执行隐式返回,格式为(value) => newvalue