我正在尝试在React中为我创建的一些JSON内容创建一个double for循环:
"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>
)
}
但是,此错误显示在浏览器中:
当我尝试渲染
<ul>
{x.subjects}
</ul>
有关为什么发生这种情况的任何指示? 我们甚至可以在JSX中使用double for循环吗?
谢谢!
答案 0 :(得分:1)
我尝试了相同的逻辑。在下面的编译器中,它工作得很好。
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"/>
答案 1 :(得分:0)
我找到了解决方案!
我想这个问题不像.map
那样重要,因为它不能完全理解我的生命周期方法。
x.subjects
是一个数组,但是在第一次渲染时未定义,因为前端尚未收到来自后端的响应。
要解决此问题,我设法执行了以下操作:
<ul>
{x.subjects === undefined ? "loading..." : x.subjects.map((y, j) => <li key={j}>{y}</li>)}
</ul>
这允许第一次渲染以避免失败。
这使我陷入另一切线,想知道这是否是加载初始状态的正确方法。现在我是:
我想知道是否有更好的方法...