React foreach in JSX

后端 未结 1 970
北海茫月
北海茫月 2020-11-29 05:04

I have a object that I want to output via REACT

question = {
    text: \"Is this a good question?\",
    answers: [
       \"Yes\",
       \"No\",
       \"I         


        
相关标签:
1条回答
  • 2020-11-29 05:21

    You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So better use map because it returns an array like this

    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;
    
    0 讨论(0)
提交回复
热议问题