const course = [{
id: 1,
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
我發現很容易映射名稱“Half Stack Application Development”和“Node.js”并通過以下方式顯示它們:
{course.map(c => <li>{c.name}</li>)}
但是,course.parts.map(c => <li>{c.name}</li>)回傳未定義。
你將如何映射它,使它看起來像
半堆疊應用程式開發
- 反應的基礎
- 使用 props 傳遞資料
- 組件的狀態
節點.js
- 路由
- 中間件
為什么 course.parts.map(p => p.name) 回傳 undefined 以及如何訪問parts陣列中的名稱?
uj5u.com熱心網友回復:
下面展示的是一個使用堆疊片段和 ReactJS (v 16.8.0) 實作所需目標的作業演示。
const Thingy = ({courses, ...props}) => {
return (
<div>
{courses.map(c => ( // iterate over the "courses" array
<div>
<h4>{c.name}</h4>
{c.parts.map(p => ( // now, for each "course", iterate over "parts" array
<li>{p.name}</li>
))}
</div>
))}
</div>
);
};
const course = [{
id: 1,
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
ReactDOM.render(
<div>
DEMO
<Thingy courses={course} />
</div>,
document.getElementById("rd")
);
<div id="rd" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
解釋
添加到上述代碼段的行內注釋。
uj5u.com熱心網友回復:
您需要在地圖中制作地圖。
這應該有效:
<ul>
{course.map(c => (
<>
<li>{c.name}</li>
<ul>
{c.parts.map(p =>
<li>{p.name}</li>)}
</ul>
</>
))}
</ul>
uj5u.com熱心網友回復:
course兩者parts都是陣列,所以你不能course.parts直接得到。您可以為如下效果圖做雙映射
{course.map(c => <>
<p>{c.name}</p>
<ul>
{c.parts.map(part => <li>{part.name}</li>)}
</ul>
</>)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466509.html
標籤:javascript 数组 反应
上一篇:無法使用ReactJS顯示影像
下一篇:獲取一個月的所有天數
