【问题标题】:forEach() in React JSX does not output any HTMLReact JSX 中的 forEach() 不输出任何 HTML
【发布时间】:2018-05-16 21:56:58
【问题描述】:

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

从上面的代码片段可以看出,我正在尝试通过在 props 中使用数组 Answers 来插入组件 Answers 的数组,它会迭代但不会输出到 HTML。

【问题讨论】:

    标签: reactjs react-props


    【解决方案1】:

    您需要将一个元素数组传递给jsx。问题是 forEach 不返回任何内容(即返回 undefined。所以最好使用map,因为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={answer} answer={answer} />) 
            })}
    }
    
    export default QuestionSet;
    

    【讨论】:

    • 在虚拟 dom 的某些情况下,使用 var i 作为键不是一个好的选择。
    • @maquannene 确实感谢您指出这一点。这是一个很好的帖子为什么medium.com/@robinpokorny/…
    • FWIW 你也可以传入其他类型的集合。您只需展开它们,以便它们与.map() 一起使用。例如Object.keys(collection).map(key =&gt; ... 并分配一个变量以便于使用collection[key]
    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 2021-01-15
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2021-12-11
    • 2016-08-07
    相关资源
    最近更新 更多