现在我们需要一个页面来展现数据库中记录的用户。
在/src/pages
下新建UserList.js
文件。
创建并导出UserList组件:
import React from 'react';
class UserList extends React.Component {
render () {
return (
...
);
}
}
export default UserList;
当页面加载的时候需要调用接口来获取用户列表,并把获取到的用户列表数据存放到组件的state中(this.state.userList):
class UserList extends React.Component {
constructor (props) {
super(props);
this.state = {
userList: []
};
}
componentWillMount () {
fetch('http://localhost:3000/user')
.then(res => res.json())
.then(res => {
this.setState({
userList: res
});
});
}
render () { ... }
}
在render
方法中,使用数组的map
方法将用户数据渲染为一个表格:
class UserList extends React.Component {
constructor (props) { ... }
componentWillMount () { ... }
render () {
const {userList} = this.state;
return (
<div>
<header>
&l