React foreach in JSX

谁都会走 提交于 2019-12-17 18:24:58

问题


I have a object that I want to output via REACT

question = {
    text: "Is this a good question?",
    answers: [
       "Yes",
       "No",
       "I don't know"
    ]
} 

and my react component (cut down), is another component

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;

as you can see from the snippit above, i'm trying to insert an array of the component Answer by using the array Answers in props, it does itterate but is not outputted into HTML.


回答1:


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;


来源:https://stackoverflow.com/questions/47616355/react-foreach-in-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!