在JSX中反应foreach

时间:2017-12-03 07:44:24

标签: reactjs react-props

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

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

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

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;

从上面的snippit可以看出,我正在尝试插入组件的数组通过在道具中使用数组Answers,它会进行itterate但不会输出到HTML中。

1 个答案:

答案 0 :(得分:75)

您需要将一个元素数组传递给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;