For..in仅返回第一项-React js

时间:2018-11-28 00:08:45

标签: javascript for-in-loop

我正在遍历一个对象以返回值。当我用console.log结果时,代码可以正常工作,但是当我尝试将其呈现为文本时,代码将无法工作。由于某种原因,它仅返回第一个值。我在做什么错了?

代码如下:

  testFunc = () => {

let spaceship = {
    crew: {
    captain: {
        name: 'Lily',
        degree: 'Computer Engineering',
        cheerTeam() { console.log('You got this!') }
        },
    'chief officer': {
        name: 'Dan',
        degree: 'Aerospace Engineering',
        agree() { console.log('I agree, captain!') }
        },
    medic: {
        name: 'Clementine',
        degree: 'Physics',
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna',
        degree: 'Conservation Science',
        powerFuel() { console.log('The tank is full!') }
        }
    }
};

for(let crewMember in spaceship.crew){
   return spaceship.crew[crewMember].name
}

 }


render(){
  return(
    <div>
     {this.testFunc()}
    </div>
  )
}

无法渲染的新代码

  testFunc = () => {

let spaceship = {
    crew: {
    captain: {
        name: 'Lily',
        degree: 'Computer Engineering',
        cheerTeam() { console.log('You got this!') }
        },
    'chief officer': {
        name: 'Dan',
        degree: 'Aerospace Engineering',
        agree() { console.log('I agree, captain!') }
        },
    medic: {
        name: 'Clementine',
        degree: 'Physics',
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna',
        degree: 'Conservation Science',
        powerFuel() { console.log('The tank is full!') }
        }
    }
};

return Object.entries(spaceship.crew).map(member =>  member.name)

}

render(){     返回(                 {this.testFunc()}            )   }

1 个答案:

答案 0 :(得分:1)

问题在于,在for循环的第一次迭代中,该函数返回并结束。可能的解决方案是:

testFunc = () => {

   let spaceship = {
      crew: {
         captain: {
            name: 'Lily',
            degree: 'Computer Engineering',
            cheerTeam() { console.log('You got this!') }
         },
         'chief officer': {
            name: 'Dan',
            degree: 'Aerospace Engineering',
            agree() { console.log('I agree, captain!') }
         },
         medic: {
            name: 'Clementine',
            degree: 'Physics',
            announce() { console.log(`Jets on!`) } },
            translator: {
               name: 'Shauna',
               degree: 'Conservation Science',
               powerFuel() { console.log('The tank is full!') }
            }
         }
   };
   var names = []
   for(var key in spaceship.crew){
       names.push(spaceship.crew[key].name)
   }

   return names // Return an array with the names
}

然后,在渲染中,您应该执行以下操作:

render(){
   return(
      <div>
         {this.testFunc().map(name => <p> name </p>)}
      </div>
   )
}