gpt4 book ai didi

reactjs - 如何在 react 中循环嵌套数组?

转载 作者:行者123 更新时间:2023-12-02 03:30:12 25 4
gpt4 key购买 nike

假设我将此常见问题解答数组作为我的状态之一:

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>
);
}

但是,由于嵌套的map函数,出现了错误:

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

如何正确循环这个嵌套对象?

最佳答案

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

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>
);

}

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

关于reactjs - 如何在 react 中循环嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com