React JSX 中的 forEach() 不输出任何 HTML

forEach() in React JSX does not output any HTML

我有一个对象想通过 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;

正如您从上面的代码片段中看到的那样,我试图通过在道具中使用数组 Answers 来插入一个组件 Answer 的数组,它会迭代但不会输出到 HTML.

您需要将元素数组传递给 jsx。问题是 forEach 没有 return 任何东西(即 returns undefined。所以最好使用 map 因为 map return 是一个数组:

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={answer} answer={answer} />) 
        })}
}

export default QuestionSet;