userlist
import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { getUserListAction, delUserListAction, addUserListAction, getRoleListAction, editUserListAction, getRegionsAction } from '../../../redux/ActionCreator/UserListAction'
// import http from '../../../util/http';
import { Table, Button, Switch, Modal, Form, Select, Input } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
const { Option } = Select;
function UserList (props) {
/**模态框配置**/
const [visibleModal, setVisibleModal] = useState(false)
const [currentId, setcurrentId] = useState()
const [title, seTtitle] = useState("")
const [form] = Form.useForm();
// 取 users 列表数据
// const { rolelist } = props
useEffect(() => {
props.getUserListAction() // 通过react-redux action 异步获取数据
}, [])
// 取 角色 列表数据
useEffect(() => {
props.getRoleListAction() // 通过react-redux action 异步获取数据
}, [])
// 取区域regions数据
useEffect(() => {
props.getRegionsAction()
}, [])
const columns = [
{
title: '区域',
dataIndex: 'region',
render: (region) => {
return <b>{region === "" ? "全球" : region}</b>
}
},
{
title: '角色名称',
dataIndex: 'role',
render: (role) => {
return <div>{role ? role.roleName : ''}</div>
}
},
{
title: '用户名',
dataIndex: 'username'
},
{
title: '用户状态',
render: (item) => {
return <Switch checked={item.roleState} disabled={item.default} onChange={(switchChecked) => {
}}>
</Switch>
}
},
{
title: "操作",
render: (item) => {
return <div>
<Button shape="circle" icon={<DeleteOutlined />} danger onClick={() => handleDelete(item)} disabled={item.default} />
<Button shape="circle" type="primary" icon={<EditOutlined />} disabled={item.default} onClick={() => handleEdit(item)} />
</div>
}
}
];
/**=========================模态框form处理开始===================**/
// 初始化form 数据
const initFormData = (item) => {
if (item.id) { // 编辑用户 对表单进行数据回显
form.setFieldsValue({ username: item.username })
form.setFieldsValue({ password: item.password });
form.setFieldsValue({ region: item.region === "" ? "全球" : item.region });
form.setFieldsValue({ roleId: item.roleId });
} else { // 添加用户
form.resetFields() // 重置表单
}
}
//编辑
const handleEdit = (item) => { // item 点击那一行的对象
seTtitle("编辑用户")
setcurrentId(item.id)
setVisibleModal(true)
initFormData(item)
}
// 弹出框点击确认触发
const handleModalOk = () => {
form.validateFields() // 触发校验,成功走.then,失败.catch
.then(values => {
form.resetFields(); // 重置表单
setVisibleModal(false) // 隐藏model
if (title === '添加用户') {
props.addUserListAction(values)
} else { // 编辑用户
props.editUserListAction(currentId, values)
}
}).catch(err => {
console.log('Validate Failed:', err);
})
}
// 弹出框点击取消触发
const handleModalCancel = () => {
setVisibleModal(false)
}
// 删除
const handleDelete = (item) => {
Modal.confirm({
icon: <ExclamationCircleOutlined />,
content: '是否删除用户',
okText: '确认',
cancelText: '取消',
onOk: () => { // 点击确认调用 delUserListAction
props.delUserListAction(item)
}
});
}
return (
<div>
<div>
<Button type="primary"
style={{ marginBottom: "10px" }}
onClick={() => {
seTtitle("添加用户")
setVisibleModal(true)
initFormData({})
}} > 添加用户</Button>
{/* 模态框 */}
<Modal
title={title}
visible={visibleModal}
onOk={handleModalOk}
onCancel={handleModalCancel}
okText="确认"
cancelText="取消"
>
<Form
form={form}
layout="vertical"
name="form_in_modal"
>
<Form.Item
name="username"
label="用户名"
rules={[{ required: true, message: 'Please input the title of collection!' }]}
>
<Input />
</Form.Item>
<Form.Item
name="password"
label="密码"
rules={[{ required: true, message: 'Please input the title of collection!' }]}
>
<Input type="password" />
</Form.Item>
<Form.Item
name="region"
label="区域"
rules={[{ required: true, message: 'Please input the title of collection!' }]}
>
<Select>
{
props.regionList.map(item =>
<Option value={item.value} key={item.id}>{item.title}</Option>
)
}
</Select>
</Form.Item>
<Form.Item
name="roleId"
label="角色"
rules={[{ required: true, message: 'Please input the title of collection!' }]}
>
<Select>
{
props.rolelist.map(item =>
<Option value={item.id} key={item.id}>{item.roleName}</Option>
)
}
</Select>
</Form.Item>
</Form>
</Modal>
<Table dataSource={props.dataSource}
columns={columns}
rowKey={(item) => item.id}
pagination={ // 分页器
{
pageSize: 10
}
}
/>
</div>
</div>
)
}
const mapStateToProps = (state) => { // 映射状态到属性(state store中的状态)
return {
dataSource: state.UserlistReducer.datalist,
rolelist: state.UserlistReducer.rolelist,
regionList: state.UserlistReducer.regionList
}
}
const mapStateToDispatch = { // 通过connect dispatch(UserList)
getUserListAction,
addUserListAction,
editUserListAction,
delUserListAction,
getRoleListAction,
getRegionsAction
}
export default connect(mapStateToProps, mapStateToDispatch)(UserList)
action
import http from "../../util/http"
//获取user 列表数据
function getUserListAction () {
return http.get("/users?_expand=role").then(res => {
// console.log(res.data)
return {
type: "get_list",
payload: res.data
}
}) // 返回的是一个promise对象
}
//获取role 列表数据
function getRoleListAction () {
return http.get("/roles").then(res => {
// console.log(res.data)
return {
type: "get_role_list",
payload: res.data
}
}) // 返回的是一个promise对象
}
//获取 region 列表数据
function getRegionsAction () {
return http.get("/regions").then(res => {
return {
type: "get_regions_list",
payload: res.data
}
})
}
// 添加用户
function addUserListAction (values) {
return http.post("/users", {
...values,
"roleState": true,
"default": false
}).then(res => {
// 新增数据需要对状态重新赋值,改变状态在UserListReducer中进行
return {
type: "add_list",
payload: res.data
}
})
}
// 编辑用户
function editUserListAction (currentId, values) {
console.log(currentId);
// return http.patch(`/users/${currentId}`, values).then(res => {
// return {
// type: "edit_list",
// payload: res.data
// }
// })
// http.patch(`/users/${currentId}`, values).then(res => {
// console.log(res.data);
// // 追加role 字段
// //1. 因为datasource数组里的每一个元素对象里都又role属性
// //2. res.data返回的是用户对象(即数据库里存储的用户对象),该对象里没有role属性
// let obj = res.data
// obj.role = roleList.filter(item => item.id === res.data.roleId)[0]
// setDataSource(dataSource.map(item => {
// if (item.id === currentId) {
// return { ...item, ...obj }
// }
// return item
// }))
// })
}
// 删除用户
function delUserListAction (item) {
return http.delete(`/users/${item.id}`).then(res => {
return {
type: "del_list",
payload: res.data
}
})
// http.delete(`/users/${item.id}`).then(res => {
// var list = dataSource.filter(data => item.id !== data.id)
// setDataSource(list)
// })
}
export { getUserListAction, delUserListAction, addUserListAction, editUserListAction, getRoleListAction, getRegionsAction }
reducer
const UserlistReducer = (prevState = {
datalist: [], //
rolelist: [], // 角色
regionList: [] // 区域
}, action) => {
let newState = { ...prevState } // 深复制,后期只能改newState
// 改变状态
let { type, payload } = action
switch (type) { // type从dispatch 中传入
// ---- 获取数据 -----
case "get_list":
// newState = {}
// console.log(newState);
newState.datalist = payload
return newState
case "get_role_list":
newState.rolelist = payload
return newState
case "get_regions_list":
// console.log(payload);
newState.regionList = payload
return newState
//---- 添加用户 ----
case "add_list":
// payload === res.data
// 重新post 的没有 role 属性, 需要添加 role 字段
payload.role = newState.rolelist.filter(item => item.id === payload.roleId)[0]
newState.datalist = [...newState.datalist, payload]
return newState
//---- 编辑用户 ----
case "edit_list":
let a = newState.datalist.map(item => {
if (item.id === payload.id) {
item = payload
}
return item
})
newState.rolelist = a
return newState
//---- 删除用户 ----
case "del_list":
// console.log(newState);
// newState = {}
// console.log(newState);
var list = newState.datalist.filter(data => payload.id !== data.id)
newState.datalist = list
return newState
default:
return prevState // 默认没改的 return 老状态
}
}
export default UserlistReducer