在JSX中反应foreach

mic*_*ael 59 reactjs react-props

我有一个我想通过REACT输出的对象

question = {
    text: "Is this a good question?",
    answers: [
       "Yes",
       "No",
       "I don't know"
    ]
} 
Run Code Online (Sandbox Code Playgroud)

而我的反应成分(减少)是另一个组成部分

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.forEach(answer => {     
           console.log("Entered");  //This does ifre                       
           <Answer answer={answer} />   //THIS DOES NOT WORK 
        })}
}

export default QuestionSet;
Run Code Online (Sandbox Code Playgroud)

正如你从上面的snippit中看到的那样,我正在尝试插入组件的数组通过在道具中使用数组Answers,它确实是itterate但不输出到HTML中.

Pra*_*rma 111

您需要传递一个元素数组jsx.问题是forEach不返回任何东西(即它返回undefined).所以更好用,map因为它返回一个这样的数组

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={i} answer={answer} />) 
        })}
}

export default QuestionSet;
Run Code Online (Sandbox Code Playgroud)

  • 在某些情况下,使用 var i 作为 key 对于虚拟 dom 不是一个好的选择。 (9认同)
  • @maquannene 确实感谢您指出这一点。这是一篇关于为什么的好文章https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318 (4认同)
  • FWIW 您还可以传递其他类型的集合。您只需展开它们,以便它们可以与“.map()”一起使用。例如 `Object.keys(collection).map(key =&gt; ...` 并分配一个变量以便方便地使用 `collection[key]` (2认同)