React中对象键循环不渲染

3

我不确定我的代码有什么问题,但是我无法使一个简单的 div 在对象键循环中渲染。我知道它循环了11次,因为我已经在其中放置了一个控制台日志,并输出了7次控制台日志,但是这个 div 根本没有渲染。任何想法:

class BookingView extends React.Component {
render () {
  const {color, booking} = this.props
  return (
    <div>
      <BookingHeader booking={booking} color={color}/>
      {Object.keys(booking).forEach(function(key,index) {
        <div>this is a test</div>
      })}
    </div>
  )
}
}
3个回答

11

forEach 不会返回任何数组。使用 map 取而代之,像这样:

{Object.keys(booking).map(function(key,index) {
   return (<div key={key}>this is a test</div>)
})}

谢谢,我尝试在过去一小时内使用for each。感谢您的帮助。 - Mitesh K

7
因为#array.forEach返回的是undefined,所以使用#array.map从回调函数中返回自定义元素,最终map将返回所有元素的数组。
{
    Object.keys(booking).map((key,index)  => <div key={key}>this is a test</div>)
}

还需要在每个动态生成的元素中添加 key 属性。


3
< p > forEach 返回 undefined,React 不会渲染。

您可能想要:

  1. 使用 map,并且

  2. 从回调函数中返回一些内容

例如,使用箭头函数(简洁形式具有隐式的 return):

class BookingView extends React.Component {
  render () {
    const {color, booking} = this.props
    return (
      <div>
        <BookingHeader booking={booking} color={color}/>
        {Object.keys(booking).map(key => <div key={key}>this is a test</div>)}
      </div>
    )
  }
}
< p > < em > (请注意我添加了key属性,因为在呈现列表时需要。)

或者是一个带有明确返回的冗长箭头:

class BookingView extends React.Component {
  render () {
    const {color, booking} = this.props
    return (
      <div>
        <BookingHeader booking={booking} color={color}/>
        {Object.keys(booking).map(key => {
          return <div key={key}>this is a test</div>;
        })}
      </div>
    )
  }
}

...或者像你的问题中一样使用 function 函数:

class BookingView extends React.Component {
  render () {
    const {color, booking} = this.props
    return (
      <div>
        <BookingHeader booking={booking} color={color}/>
        {Object.keys(booking).map(function(key) {
          return <div key={key}>this is a test</div>;
        })}
      </div>
    )
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接