如何循环嵌套数组在反应?

时间:2018-08-28 04:09:33

标签: reactjs loops nested-loops

假设我将这种常见问题数组作为我的一种状态:

this.state = {
    faqs: [
        {
            section: "Section One",
            faqList: [
                {
                    question: "Q1",
                    answer: "A1"
                },
                {
                    question: "Q1",
                    answer: "A1"
                }
            ]
        },
        {
            section: "Section Two",
            faqList: [
                {
                    question: "Q1",
                    answer: "A1"
                },
                {
                    question: "Q1",
                    answer: "A1"
                }
            ]
        }
    ]
}

我想渲染它们。这是我目前尝试执行的操作:

render() {

    const faqs = this.state.faqs;

    return (
    <div>   
        {faqs.map(faqSec => {

            return (
                <h2>{faqSec.section}</h2>

                {faqSec.faqList.map(faq => {
                    return (
                        <p>faq.question</p> 
                        <p>faq.answer</p>                                           
                    )
                })}

            )
        })}
    </div>
    );
}

但是,由于嵌套的地图函数而发生错误:

SyntaxError: Unexpected token, expected , (80:8)

如何正确遍历此嵌套对象?

2 个答案:

答案 0 :(得分:1)

您需要在根元素中返回地图结果列表:

return (
  <div>{/* use key here */}
   <h2>{faqSec.section}</h2>
   {faqSec.faqList.map(faq => {
     return (
      <div>{/* use key here */}
       <p>faq.question</p>
       <p>faq.answer</p>                                           
      </div>
     )
   })}
 </div>
)

或者,您可以返回元素数组:

return [
   <h2>{faqSec.section}</h2>,{/* use key here */}
   {faqSec.faqList.map(faq => {
     return [
       <p>faq.question</p>,{/* use key here */}
       <p>faq.answer</p>{/* use key here */}
     ]
   })}
 ]

或者,即使您可以使用Fragment

return (
      <React.Fragment>{/* use key here */}
       <h2>{faqSec.section}</h2>
       {faqSec.faqList.map(faq => {
         return (
          <React.Fragment>{/* use key here */}
           <p>faq.question</p>
           <p>faq.answer</p>                                           
          </React.Fragment>
         )
       })}
     </React.Fragment>
    )

您也可以对<React.Fragment></React.Fragment>使用简写语法:

<></>

并非所有工具都支持简写语法。如果要使用速记语法,请参见this

确保如上所述唯一地使用密钥。

答案 1 :(得分:1)

您必须将标签放在父标签中。 React不会单独打印这两个标签。您必须将这两个标签与父标签绑定。

render() {

const faqs = this.state.faqs;

return (
 <div>   
    {faqs.map(faqSec => {

        return (
           <div>
              <h2>{faqSec.section}</h2>

              {faqSec.faqList.map(faq => {
                  return (
                     <div>
                        <p>{faq.question}</p> 
                        <p>{faq.answer}</p> 
                     </div>                                          
                  )
              })}
          </div>
        )
    })}
</div>
);

}

您还错过了代码中的{}括号。请检查此代码。希望它对您有用。