现在我们需要一个页面来展现数据库中记录的用户。
在/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>
<

本文介绍如何在React应用中实现用户列表的渲染。通过创建UserList组件,从API获取用户数据并存储在状态中,使用map方法动态渲染表格。同时,结合react-router进行页面路由设置,确保添加用户后能无缝跳转到用户列表页面,实时展示新增用户。

2万+





