gpt4 book ai didi

javascript - 使用 .map 在 React 中使用 double for 循环

转载 作者:行者123 更新时间:2023-11-30 20:12:54 31 4
gpt4 key购买 nike

我正在尝试在 React 中为我创建的一些 JSON 内容创建一个双循环:

"students": [
{
"name": "person",
"photoURL": "https://via.placeholder.com/100x100",
"subjects":[
"physics",
"math",
"english"
],
"nextClass": "August 29th, 2018"
},
{
"name": "human",
"photoURL": "https://via.placeholder.com/100x100",
"subjects":[
"chemistry",
"math",
"french"
],
"nextClass": "August 27th, 2018"
}]

在我的 JSX 中,我试图遍历学生对象,然后再次遍历所有主题以生成一个无序列表:

render(){

return(
<div id="display-students">
{this.props.students.map((x,i) =>{
return (
<div className="student" key={i}>
<h2>{x.name}</h2>
<img src={x.photoURL} alt="profile"/>
<h3>Subjects: </h3>
<ul>
{x.subjects.map((y) => <li>{y}</li>)}
</ul>
</div>
)
})}
</div>
)
}

但是,这个错误出现在浏览器中:

enter image description here

当我尝试渲染时

<ul>
{x.subjects}
</ul>

我看到数组中的内容全部混合成一个字符串: enter image description here

关于为什么会发生这种情况的任何指示?我们甚至可以在 JSX 中使用双 for 循环吗?

提前致谢!

最佳答案

我试过同样的逻辑。它在下面的编译器中工作得很好。

let students = [
{
"name": "person",
"photoURL": "https://via.placeholder.com/100x100",
"subjects":[
"physics",
"math",
"english"
],
"nextClass": "August 29th, 2018"
},
{
"name": "human",
"photoURL": "https://via.placeholder.com/100x100",
"subjects":[
"chemistry",
"math",
"french"
],
"nextClass": "August 27th, 2018"
}]

const Component = (props) => {

return(
<div id="display-students">
{props.students.map((x,i) =>{
return (
<div className="student" key={i}>
<h2>{x.name}</h2>
<img src={x.photoURL} alt="profile"/>
<h3>Subjects: </h3>
<ul>
{x.subjects.map((y) => <li>{y}</li>)}
</ul>
</div>
)
})}
</div>
)
}

ReactDOM.render(<Component students={students} />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="app"/>

关于javascript - 使用 .map 在 React 中使用 double for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213530/

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