React 基础巩固(十三)——列表渲染
列表渲染
- 在 React 中没有像 Vue 模块语法中的 v-for 指令,而是需要我们通过 JS 代码的方式组织数据,转成 JSX
- 在 React 中,展示列表最多的方式就是使用数组的 map 高阶函数
- 在展示数组前,有时会进行一些处理
- 过滤一些内容(filter 函数)
- 截取数组中的一部分内容(slice 函数)
- 列表中的 key
- 子项一般需要绑定 key,否则存在 Warning 警告(Each child in a list should have a unique “key”)
- key主要作用是为了提高diff算法时的效率
<script type="text/babel">
const root = ReactDOM.createRoot(document.querySelector("#root"));
class App extends React.Component {
constructor() {
super();
this.state = {
students: [
{ id: 111, name: "outman1", score: 99 },
{ id: 112, name: "outman2", score: 98 },
{ id: 113, name: "outman3", score: 194 },
{ id: 113, name: "outman4", score: 196 },
{ id: 113, name: "outman5", score: 126 },
{ id: 113, name: "outman6", score: 136 },
],
};
}
render() {
const { students } = this.state;
const filterStudents = students.filter((item) => item.score > 100);
const sliceStudents = filterStudents.slice(0, 2);
return (
<div>
<h2>学生列表数据</h2>
<div className="list">
{sliceStudents.map((item) => {
return (
<div className="item" key={item.id}>
<h2>学号: {item.id}</h2>
<h2>姓名: {item.name}</h2>
<h2>分数: {item.score}</h2>
</div>
);
})}
</div>
</div>
);
}
}
root.render(<App />);
</script>