一、React 结合 Antd 实现表格的渲染、新增、修改和删除
- 引入所需相关的组件和文件,代码如下所示:
import React, {
Component } from 'react'
import {
Card, Button, Table, Modal, message } from 'antd'
import LinkButton from '../../components/linkButton/index'
import {
formateDate } from '../../utils/dateUtils'
import {
reqUsers, reqDeleteUser, reqAddOrUpdateUser } from '../../api'
import {
PAGE_SIZE } from '../../utils/constants'
import UserForm from './userForm'
- 创建
User
组件,定义初始化的 state
。users
为所有用户列表,默认为空数组。roles
为所有角色列表,默认为空数组。isShow
为是否显示确认框,默认为 false
,代码如下所示:
state = {
users: [],
roles: [],
isShow: false,
}
- 在
User
组件中,通过 initColumns
初始化表格列,最后返回的 this.columns
就是表格显示的列,代码如下所示:
initColumns = () => {
this.columns = [
{
title: '用户名',
dataIndex: 'username'
},
{
title: '邮箱',
dataIndex: 'email'
},
{
title: '电话',
dataIndex: 'phone'
},
{
title: '注册时间',
dataIndex: 'create_time',
render: formateDate
},
{
title: '所属角色',
dataIndex: 'role_id',
render: (role_id) => this.roleNames[role_id]
},
{
title: '操作',
render: (user) => (
<span>
<LinkButton onClick={
() => this.showUpdate(user)}>修改</LinkButton>
<LinkButton onClick={
() => this.deleteUser(user)}>删除</LinkButton>
</span>
)
}
]
}
- 在
User
组件中,定义 initRoleNames
方法,根据 role
的数组, 生成包含所有角色名的对象,属性名用角色 id
值,最后通过 this.roleNames
保存 roleNames
,在 initColumns
方法中的所属角色调用。showUpdate
是显示修改界面,保存 user
,通过 setState
设置 isShow
为 true
。showAdd
是显示添加界面,去除前面保存的user
,通过 setState
设置 isShow
为 true
。showUpdate
和 showAdd
也会在 initColumns
方法中的操作调用,代码如下所示:
initRoleNames = (roles) => {
const roleNames = roles.reduce((pre, role) => {
pre[role._id] = role.name
return pre
}, {
})
this.roleNames = roleNames
}
showUpdate = (user) => {
this.user = user
this.setState({
isShow: true })
}
showAdd = () => {
this.user = null
this.setState({
isShow: true })
}
- 在
User
组件中,定义 getUsers
方法,获取所有的用户列表。发起请求,如果 result.status
为 0,说明请求成功,将 result.data
结构获得 users
和 roles
,通过 setState
设置 state
中的 users
和 roles
,代码如下所示:
getUsers = async () => {
const result = await reqUsers()
if (result.status === 0) {
const {
users, roles } = result.data
this.setState({
users,
roles
})
}
}
- 在
componentWillMount
生命周期中,调用 initColumns()
,初始化表格列。在 componentDidMount
生命周期中,调用 getUsers()
,获取所有的用户列表,代码如下所示:
componentWillMount () {
this.initColumns()
}
componentDidMount