显示学生列表[demo]
这篇博客主要是对React组件相关知识的一个总结。 思路:先考虑Student组件怎么写,再考虑一个StudentList组件应该如何用Student组件完成,其中关键之处是组件属性的使用。
一、需求
- 通过接口拿到学生列表数据,并将其渲染到页面上。
import React from "react";
export default function Student(props) {
return (
<div>
<li>
[姓名]:{props.name},
[性别]:{props.sex === 0 ? "男" : "女"},
[年龄]:{new Date().getFullYear() - props.birth},
[邮件]:{props.email},
[电话]:{props.phone},
[学号]:{props.sNo}
</li>
</div>
);
}
import React, { Component } from 'react'
import Student from './Student';
export default class StudentList extends Component {
render() {
const students = this.props.stus.map((item,i)=><Student {...item} key={i}/>)
return (
<ul>
{}
{students}
</ul>
)
}
}
import React from "react";
import ReactDOM from "react-dom";
import StudentList from "./components/StudentList";
const appkey = "xxxxx";
async function fetchAllStudents() {
const stus = fetch(
"http://open.xxx.com//api/student/findAll?appkey=" + appkey
)
.then((resp) => resp.json())
.then((resp) => resp.data);
return stus;
}
async function render() {
const stus = await fetchAllStudents();
ReactDOM.render(
<StudentList stus = {stus}></StudentList>,
document.getElementById("root")
);
}
render();
二、效果
- 通过接口拿到的数据如下
 - 页面渲染如下
 - 控制台报错如下:渲染列表时,列表项不加key值会报警告

三、总结
- 我们在写组件是先考虑好需要传入的数据格式,数据格式的处理部分放到父组件,子组件只负责拿到数据,并将其进行渲染即可。
- 如果想要渲染列表,那么我们可以把所有列表项(React元素)放到一个数组里,然后直接把数组放到JSX表达式中即可。因为浏览器会遍历数组,将每一个数组元素单拿出来作为子元素添加到JSX中。
- 用fetch()获取数据,基本fetch请求格式。
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
四、参考
- MDN:使用 Fetch
|