项目实战 - 用户列表

用户列表想要实现这样的效果: 

渲染数据:

import React,{useState,useEffect} from 'react';
import { Button,Table, Tag,Modal,Popover, Switch } from 'antd';
import { EditOutlined,DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { data } from 'react-router-dom';
import Item from 'antd/es/list/Item';
const { confirm } = Modal;function UserList() {const [dataSource,setdataSource]=useState([])useEffect(()=>{axios.get("http://localhost:3000/users?_expand=role").then(res=>{console.log(res.data);const list = res.datasetdataSource(list)})},[])const columns = [{title: '区域',dataIndex: 'region',render:(region)=>{return <b>{region===""?'全球':region}</b>}},{title: '角色名称',dataIndex: 'role',render:(role)=>{return role?.roleName}},{title: '用户名',dataIndex: 'username',},{title:"用户状态",dataIndex:"roleState",render:(roleState,item)=>{return <Switch checked={roleState} disabled={item.default}></Switch>}},{title: '操作',render:(record)=>{return <div><Button type="primary" shape="circle" icon={<EditOutlined />} disabled={record.default} /><Button danger type="primary" shape="circle" icon={<DeleteOutlined />} disabled={record.default}/></div>}},];const deleteMethod = (record) => {console.log(record);}return (<div><Button></Button><Table dataSource={dataSource} columns={columns}pagination={{pageSize:5 }}>rowKey = {item => item.id}</Table></div>)
}export default UserList;

接下来我逐步完成增删改查的功能

增数据需要用到弹出型的新增表单:

还需要从后端拿取数据,所以定义新的状态: 

import React,{useState,useEffect,useRef} from 'react';
import { Button,Table, Tag,Modal,Popover, Switch,Form,Input,Radio,Select } from 'antd';
import { EditOutlined,DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { data } from 'react-router-dom';
import Item from 'antd/es/list/Item';
import UserForm from '../../../components/user-manage/UserForm';const { confirm } = Modal;
function UserList() {const [dataSource,setdataSource]=useState([])const [isAddVisible,setisAddVisible]=useState(false)const [roleList,setroleList]=useState([])const [regionList,setregionList]=useState([])const addForm = useRef(null)useEffect(()=>{axios.get("http://localhost:3000/users?_expand=role").then(res=>{// console.log(res.data);const list = res.datasetdataSource(list)})},[])useEffect(()=>{axios.get("http://localhost:3000/regions").then(res=>{// console.log(res.data);const list = res.datasetregionList(list)})},[])useEffect(()=>{axios.get("http://localhost:3000/roles").then(res=>{// console.log(res.data);const list = res.datasetroleList(list)})
},[])const columns = [{title: '区域',dataIndex: 'region',render:(region)=>{return <b>{region===""?'全球':region}</b>}},{title: '角色名称',dataIndex: 'role',render:(role)=>{return role?.roleName}},{title: '用户名',dataIndex: 'username',},{title:"用户状态",dataIndex:"roleState",render:(roleState,item)=>{return <Switch checked={roleState} disabled={item.default}></Switch>}},{title: '操作',render:(record)=>{return <div><Button type="primary" shape="circle" icon={<EditOutlined />} disabled={record.default} /><Button danger type="primary" shape="circle" icon={<DeleteOutlined />} disabled={record.default}/></div>}},];const deleteMethod = (record) => {// console.log(record);}const [open, setOpen] = useState(false);return (<div><Button type='primary' onClick={() => setOpen(true)}>添加用户</Button><Table dataSource={dataSource} columns={columns}pagination={{pageSize:5 }}>rowKey = {item => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={()=>{addForm.current.validateFields().then((value)=>{console.log(value);}).catch((errInfo)=>{console.log(errInfo);})}}destroyOnClosemodalRender={(dom) => (<Formlayout="vertical">{dom}</Form>)}><UserForm regionList={regionList} roleList={roleList}ref={addForm}></UserForm></Modal></div>)
}export default UserList;

 把Form单独抽象成组件:

import React, { forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select } from 'antd';const UserForm = forwardRef((props, ref) => {const [form] = Form.useForm();// 让外部 ref 访问 form 的方法useImperativeHandle(ref, () => ({validateFields: () => form.validateFields(),resetFields: () => form.resetFields(),}));// 选择框事件const onChange = (value) => {console.log(`selected ${value}`);};return (<Form form={form} layout="vertical"> {/* 用户名 */}<Form.Itemname="username"label="用户名"rules={[{ required: true, message: '请输入用户名' }]}><Input placeholder="请输入用户名" /></Form.Item>{/* 密码 */}<Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item>{/* 区域选择 */}<Form.Itemname="region"label="区域"rules={[{ required: true, message: '请选择区域' }]}><SelectshowSearchplaceholder="请选择区域"optionFilterProp="label"onChange={onChange}options={props.regionList.map(item => ({value: item.id,label: item.value,}))}/></Form.Item>{/* 角色选择 */}<Form.Itemname="roleId"label="角色"rules={[{ required: true, message: '请选择角色' }]}><SelectshowSearchplaceholder="请选择角色"optionFilterProp="label"onChange={onChange}options={props.roleList.map(item => ({value: item.id,label: item.roleName,}))}/></Form.Item></Form>);
});export default UserForm;

这个UserForm组件需要使用forwardRef,这样才可以把ref传递出去,以及遇到的bug:穿出去值了但是打印出结果是空数组: 

修改后就是暴露方法,把之前的div去掉,以及useForm()绑定Form组件

接下来实现超级管理员禁用地区的功能,定义状态禁用

介绍一下Form组件,在 antd 中,我们可以使用 Form.useForm() 来创建一个受控的表单实例:

import { Form, Input, Button } from 'antd';const MyForm = () => {const [form] = Form.useForm(); // 创建表单实例const handleSubmit = () => {form.validateFields().then(values => {console.log('提交的数据:', values);}).catch(error => {console.log('表单验证失败:', error);});};return (<Form form={form} layout="vertical"><Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}><Input placeholder="请输入用户名" /></Form.Item><Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item><Button type="primary" onClick={handleSubmit}>提交</Button></Form>);
};

Form的一些常用方法:

 加上处理的逻辑,角色和区域的事件应该分开写,改变区域设定的规则,如果是超级管理员的话不能选择区域也可以使表单成功的提交

import React, { useState,forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select } from 'antd';// 封装一下
const UserForm = forwardRef((props, ref) => {// 使用forwardRef 可以让子组件获取父组件的方法const [form] = Form.useForm();// 让外部 ref 访问 form 的方法useImperativeHandle(ref, () => ({validateFields: () => form.validateFields(),resetFields: () => form.resetFields(),}));const [isDisabled, setIsDisabled] = useState(false);// 选择框事件// 角色选择事件
const handleRoleChange = (value) => {if (value === 1) { setIsDisabled(true);form.setFieldsValue({ region: "" }); // 清空区域} else {setIsDisabled(false);}};// 区域选择事件 (不影响角色逻辑)const handleRegionChange = (value) => {console.log("区域选择:", value);};return (<Form form={form} layout="vertical"> {/* 用户名 */}<Form.Itemname="username"label="用户名"rules={[{ required: true, message: '请输入用户名' }]}><Input placeholder="请输入用户名" /></Form.Item>{/* 密码 */}<Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item>{/* 区域选择 */}<Form.Itemname="region"label="区域"rules={isDisabled?[]:[{ required: true, message: '请选择区域' }]}><Selectdisabled={isDisabled}showSearchplaceholder="请选择区域"optionFilterProp="label"onChange={handleRegionChange}options={props.regionList.map(item => ({value: item.id,label: item.value,}))}/></Form.Item>{/* 角色选择 */}<Form.Itemname="roleId"label="角色"rules={[{ required: true, message: '请选择角色' }]}><SelectshowSearchplaceholder="请选择角色"optionFilterProp="label"onChange={handleRoleChange}options={props.roleList.map(item => ({value: item.id,label: item.roleName,}))}/></Form.Item></Form>);
});export default UserForm;

现在想要将改动同步到页面上:

import React, { useState, useEffect, useRef } from 'react'
import {Button,Table,Tag,Modal,Popover,Switch,Form,Input,Radio,Select,
} from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import { data } from 'react-router-dom'
import Item from 'antd/es/list/Item'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return <Switch checked={roleState} disabled={item.default}></Switch>},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}/></div>)},},]const deleteMethod = (record) => {// console.log(record);}const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 idconst selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 获取所选角色的名称const selectedRole = roleList.find(item => item.id === value.roleId)?.roleName || "";axios.post(`http://localhost:3000/users`,{...value,"roleState": true,"default": false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource, res.data])})}).catch((errInfo) => {console.log(errInfo)})}const [open, setOpen] = useState(false)return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal></div>)
}export default UserList

同步确实是同步了,可是这个角色的名称总是不显示,只有刷新一次才会正常的显示。。

这下就又要修改代码了:

import React, { useState, useEffect, useRef } from 'react'
import {Button,Table,Tag,Modal,Popover,Switch,Form,Input,Radio,Select,
} from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import { data } from 'react-router-dom'
import Item from 'antd/es/list/Item'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return <Switch checked={roleState} disabled={item.default}></Switch>},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}/></div>)},},]const deleteMethod = (record) => {// console.log(record);}const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 idconst selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 获取所选角色的名称const selectedRole = roleList.find(item => item.id === value.roleId)?.roleName || "";axios.post(`http://localhost:3000/users`,{...value,"roleState": true,"default": false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource, {...res.data,role:roleList.filter(item => item.id === value.roleId)[0],}])})}).catch((errInfo) => {console.log(errInfo)})}const [open, setOpen] = useState(false)return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal></div>)
}export default UserList

更新了dataSource的装填,就可以更新并渲染了

分为:扩展现有数据、添加新用户数据、更新状态

至此添加部分的功能都完毕了,来写删除

进行删除的判定确认,同步后端数据:

import React, { useState, useEffect, useRef } from 'react'
import {Button,Table,Tag,Modal,Popover,Switch,Form,Input,Radio,Select,
} from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import { data } from 'react-router-dom'
import Item from 'antd/es/list/Item'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const confirmMethod = (record) => {confirm({title: '确定要删除这个角色吗?',icon: <ExclamationCircleOutlined />,onOk() {deleteMethod(record)},onCancel() {console.log('取消删除')},})}const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return <Switch checked={roleState} disabled={item.default}></Switch>},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}onClick={()=>confirmMethod(record)}/></div>)},},]const deleteMethod = (record) => {// console.log(record);//页面状态+后端setdataSource(dataSource.filter((item) => item.id !== record.id))axios.delete(`http://localhost:3000/users/${record.id}`)}const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 idconst selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 获取所选角色的名称const selectedRole = roleList.find(item => item.id === value.roleId)?.roleName || "";axios.post(`http://localhost:3000/users`,{...value,"roleState": true,"default": false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource, {...res.data,role:roleList.filter(item => item.id === value.roleId)[0],}])})}).catch((errInfo) => {console.log(errInfo)})}const [open, setOpen] = useState(false)return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal></div>)
}export default UserList

改就是更改状态和更改信息 ,这是更改选择并同步到后端:

import React, { useState, useEffect, useRef } from 'react'
import {Button,Table,Tag,Modal,Popover,Switch,Form,Input,Radio,Select,
} from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import { data } from 'react-router-dom'
import Item from 'antd/es/list/Item'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const deleteMethod = (record) => {// console.log(record);//页面状态+后端setdataSource(dataSource.filter((item) => item.id !== record.id))axios.delete(`http://localhost:3000/users/${record.id}`)}const confirmMethod = (record) => {confirm({title: '确定要删除这个角色吗?',icon: <ExclamationCircleOutlined />,onOk() {deleteMethod(record)},onCancel() {console.log('取消删除')},})}const handleChange = (item)=>{// console.log(item)item.roleState = !item.roleStatesetdataSource([...dataSource])axios.patch(`http://localhost:3000/users/${item.id}`,{roleState:item.roleState})}const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return <Switch checked={roleState} disabled={item.default}onChange={()=>handleChange(item)}></Switch>},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}onClick={()=>confirmMethod(record)}/></div>)},},]const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 idconst selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 获取所选角色的名称const selectedRole = roleList.find(item => item.id === value.roleId)?.roleName || "";axios.post(`http://localhost:3000/users`,{...value,"roleState": true,"default": false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource, {...res.data,role:roleList.filter(item => item.id === value.roleId)[0],}])})}).catch((errInfo) => {console.log(errInfo)})}const [open, setOpen] = useState(false)return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal></div>)
}export default UserList

接下来实现点击编辑按钮弹出框可以修改信息的功能

在实现这个功能的时候遇到了问题,我觉得是事件绑定和useEffect的依赖项的问题,现在修改完可以成功的显示旧的数据了:

import React, {useState,forwardRef,useImperativeHandle,useEffect,
} from 'react'
import { Form, Input, Select } from 'antd'const UserForm = forwardRef((props, ref) => {const [form] = Form.useForm()const internalForm = props.form || form // 使用外部传递的 form 实例const [isDisabled, setIsDisabled] = useState(false)// useEffect(() => {//   if (props.form) {//     props.form.setFieldValue(props.initialValues)//   }//   // setIsDisabled(props.isUpdateDisabled);// }, [props.isUpdateDisabled, props.form]) // 修复 useEffect 的语法useEffect(() => {if (props.form && props.initialValues) {props.form.setFieldsValue(props.initialValues);}setIsDisabled(props.isUpdateDisabled);}, [props.isUpdateDisabled, props.form, props.initialValues]); // 确保依赖项正确useImperativeHandle(ref, () => ({validateFields: () => internalForm.validateFields(),resetFields: () => internalForm.resetFields(),setFieldsValue: (values) => internalForm.setFieldsValue(values),}))// const handleRoleChange = (value) => {//   if (value === 1) {//     setIsDisabled(true);//     form.setFieldsValue({ region: "" });//   } else {//     setIsDisabled(false);//   }// };// UserForm 组件中的角色切换逻辑const handleRoleChange = (value) => {const isSuperAdmin = value === 1 // 假设角色ID=1是超级管理员setIsDisabled(isSuperAdmin)if (isSuperAdmin) {internalForm.setFieldsValue({ region: '' }) // 清空区域选择}}const handleRegionChange = (value) => {console.log('区域选择:', value)}return (<Form form={internalForm} layout="vertical"><Form.Itemname="username"label="用户名"rules={[{ required: true, message: '请输入用户名' }]}><Input placeholder="请输入用户名" /></Form.Item>{/* <Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item> */}<Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item><Form.Itemname="region"label="区域"rules={isDisabled ? [] : [{ required: true, message: '请选择区域' }]}><Selectdisabled={isDisabled}showSearchplaceholder="请选择区域"optionFilterProp="label"onChange={handleRegionChange}options={props.regionList.map((item) => ({value: item.id,label: item.value,}))}/></Form.Item><Form.Itemname="roleId"label="角色"rules={[{ required: true, message: '请选择角色' }]}><SelectshowSearchplaceholder="请选择角色"optionFilterProp="label"onChange={handleRoleChange}options={props.roleList.map((item) => ({value: item.id,label: item.roleName,}))}/></Form.Item></Form>)
})export default UserForm
import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch, Form, Menu } from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const [isUpdateVisible, setisUpdateVisible] = useState(false)const [isUpdateDisabled, setisUpdateDisabled] = useState(false)const [form] = Form.useForm() //创建antd的form实例const updateForm = useRef(null)const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const deleteMethod = (record) => {// console.log(record);//页面状态+后端setdataSource(dataSource.filter((item) => item.id !== record.id))axios.delete(`http://localhost:3000/users/${record.id}`)}const confirmMethod = (record) => {confirm({title: '确定要删除这个角色吗?',icon: <ExclamationCircleOutlined />,onOk() {deleteMethod(record)},onCancel() {console.log('取消删除')},})}const handleChange = (item) => {// console.log(item)item.roleState = !item.roleStatesetdataSource([...dataSource])axios.patch(`http://localhost:3000/users/${item.id}`, {roleState: item.roleState,})}const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return (<Switchchecked={roleState}disabled={item.default}onChange={() => handleChange(item)}></Switch>)},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}onClick={() => handleUpdate(record)}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}onClick={() => confirmMethod(record)}/></div>)},},]const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 id// const selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 添加用户的代码逻辑const selectedRegion =regionList.find((item) => item.id === value.region)?.value || ''axios.post(`http://localhost:3000/users`, {...value,region: selectedRegion, // 存储的是区域的名称(如"华东")})// 获取所选角色的名称const selectedRole =roleList.find((item) => item.id === value.roleId)?.roleName || ''axios.post(`http://localhost:3000/users`, {...value,roleState: true,default: false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource,{...res.data,role: roleList.filter((item) => item.id === value.roleId)[0],},])})}).catch((errInfo) => {console.log(errInfo)})}const [isUpdate, setisUpdate] = useState(false)const [updateform] = Form.useForm() //创建antd的updateform实例// const handleUpdate = (item) => {//   setisUpdateVisible(true)//   setisUpdateDisabled(item.default)//   if(item.roleId === 1){//       //禁用//       setisUpdateDisabled(true)//   }//   else{//     setisUpdateDisabled(false) // 启用更新表单的编辑//   }//   setTimeout(() => {//     updateform.setFieldsValue({//       username: item.username,//       region: item.region,//       roleId: item.role?.id,//     })//   }, 100) // 增加一定的延迟确保 Modal 已渲染//   // //更新要想办法让已有数据展示出来//   // // setisUpdate(true)//   // updateform.setFieldsValue({ // 填充表单数据//   // username: item.username,//   // region: item.region,//   // roleId: item.role?.id//   // });// }// const handleUpdate = (item) => {//   setisUpdateVisible(true);//   setisUpdateDisabled(item.default);//   if (item.roleId === 1) {//     setisUpdateDisabled(true);//   } else {//     setisUpdateDisabled(false);//   }//   setTimeout(() => {//     updateform.setFieldsValue({//       username: item.username,//       region: item.region,//       roleId: item.role?.id,//       password: item.password, // 确保密码字段被正确设置//     });//   }, 100);// }const handleUpdate = (item) => {setisUpdateVisible(true);setisUpdateDisabled(item.default);setTimeout(() => {updateform.setFieldsValue({username: item.username,password: item.password, // 确保密码字段被正确设置region: item.region,roleId: item.role?.id,});}, 100); // 增加一定的延迟确保 Modal 已渲染}const [open, setOpen] = useState(false)const updateFormOk = () => {}return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal>{/* 更新  */}<Modalopen={isUpdateVisible}title="更新用户"okText="更新"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => {setisUpdateVisible(false)setisUpdateDisabled(!isUpdateDisabled)}}onOk={() => updateFormOk()}destroyOnClosemodalRender={(dom) => (<Form layout="vertical" form={updateform}>{/* //将form实例传递给Form组件 */}{dom}</Form>)}><UserFormregionList={regionList}roleList={roleList}form={updateform}isUpdateDisabled={isUpdateDisabled}></UserForm></Modal></div>)
}export default UserList

更改并且同步了后端的数据:

import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch, Form, Menu } from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const [isUpdateVisible, setisUpdateVisible] = useState(false)const [isUpdateDisabled, setisUpdateDisabled] = useState(false)const [form] = Form.useForm() //创建antd的form实例const [current,setCurrent] = useState(null)const updateForm = useRef(null)const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const deleteMethod = (record) => {// console.log(record);//页面状态+后端setdataSource(dataSource.filter((item) => item.id !== record.id))axios.delete(`http://localhost:3000/users/${record.id}`)}const confirmMethod = (record) => {confirm({title: '确定要删除这个角色吗?',icon: <ExclamationCircleOutlined />,onOk() {deleteMethod(record)},onCancel() {console.log('取消删除')},})}const handleChange = (item) => {// console.log(item)item.roleState = !item.roleStatesetdataSource([...dataSource])axios.patch(`http://localhost:3000/users/${item.id}`, {roleState: item.roleState,})}const columns = [{title: '区域',dataIndex: 'region',render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return (<Switchchecked={roleState}disabled={item.default}onChange={() => handleChange(item)}></Switch>)},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}onClick={() => handleUpdate(record)}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}onClick={() => confirmMethod(record)}/></div>)},},]const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 id// const selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 添加用户的代码逻辑const selectedRegion =regionList.find((item) => item.id === value.region)?.value || ''axios.post(`http://localhost:3000/users`, {...value,region: selectedRegion, // 存储的是区域的名称(如"华东")})// 获取所选角色的名称const selectedRole =roleList.find((item) => item.id === value.roleId)?.roleName || ''axios.post(`http://localhost:3000/users`, {...value,roleState: true,default: false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource,{...res.data,role: roleList.filter((item) => item.id === value.roleId)[0],},])})}).catch((errInfo) => {console.log(errInfo)})}const [isUpdate, setisUpdate] = useState(false)const [updateform] = Form.useForm() //创建antd的updateform实例const handleUpdate = (item) => {setisUpdateVisible(true);setisUpdateDisabled(item.default);setTimeout(() => {//保证超级管理员的区域禁用if(item.roleId === 1) {setisUpdateDisabled(true)} else {setisUpdateDisabled(false)}updateform.setFieldsValue({username: item.username,password: item.password, // 确保密码字段被正确设置region: item.region,roleId: item.role?.id,});}, 100); // 增加一定的延迟确保 Modal 已渲染setCurrent(item)}const [open, setOpen] = useState(false)const updateFormOk = () => {updateform.validateFields().then((value) => {setisUpdateVisible(false);const selectedRegion = regionList.find(region => region.id === value.region)?.value || '';setdataSource(dataSource.map((item) => {if (item.id === current.id) {return {...item,...value,region: selectedRegion, // 将区域 ID 转换为区域名称role: roleList.filter((data) => data.id === value.roleId)[0],}}return item;}));// 同步后端数据axios.patch(`http://localhost:3000/users/${current.id}`, {...value,region: selectedRegion, // 确保后端也存储区域名称});});}return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal>{/* 更新  */}<Modalopen={isUpdateVisible}title="更新用户"okText="更新"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => {setisUpdateVisible(false)setisUpdateDisabled(!isUpdateDisabled)}}onOk={() => updateFormOk()}destroyOnClosemodalRender={(dom) => (<Form layout="vertical" form={updateform}>{/* //将form实例传递给Form组件 */}{dom}</Form>)}><UserFormregionList={regionList}roleList={roleList}form={updateform}isUpdateDisabled={isUpdateDisabled}></UserForm></Modal></div>)
}export default UserList
import React, {useState,forwardRef,useImperativeHandle,useEffect,
} from 'react'
import { Form, Input, Select } from 'antd'const UserForm = forwardRef((props, ref) => {const [form] = Form.useForm()const internalForm = props.form || form // 使用外部传递的 form 实例const [isDisabled, setIsDisabled] = useState(false)// useEffect(() => {//   if (props.form) {//     props.form.setFieldValue(props.initialValues)//   }//   // setIsDisabled(props.isUpdateDisabled);// }, [props.isUpdateDisabled, props.form]) // 修复 useEffect 的语法useEffect(() => {if (props.form && props.initialValues) {props.form.setFieldsValue(props.initialValues);}setIsDisabled(props.isUpdateDisabled);}, [props.isUpdateDisabled, props.form, props.initialValues]); // 确保依赖项正确useImperativeHandle(ref, () => ({validateFields: () => internalForm.validateFields(),resetFields: () => internalForm.resetFields(),setFieldsValue: (values) => internalForm.setFieldsValue(values),}))// const handleRoleChange = (value) => {//   if (value === 1) {//     setIsDisabled(true);//     form.setFieldsValue({ region: "" });//   } else {//     setIsDisabled(false);//   }// };// UserForm 组件中的角色切换逻辑const handleRoleChange = (value) => {const isSuperAdmin = value === 1 // 假设角色ID=1是超级管理员setIsDisabled(isSuperAdmin)if (isSuperAdmin) {internalForm.setFieldsValue({ region: '' }) // 清空区域选择}}const handleRegionChange = (value) => {console.log('区域选择:', value)}return (<Form form={internalForm} layout="vertical"><Form.Itemname="username"label="用户名"rules={[{ required: true, message: '请输入用户名' }]}><Input placeholder="请输入用户名" /></Form.Item>{/* <Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item> */}<Form.Itemname="password"label="密码"rules={[{ required: true, message: '请输入密码' }]}><Input.Password placeholder="请输入密码" /></Form.Item><Form.Itemname="region"label="区域"rules={isDisabled ? [] : [{ required: true, message: '请选择区域' }]}><Selectdisabled={isDisabled}showSearchplaceholder="请选择区域"optionFilterProp="label"onChange={handleRegionChange}options={props.regionList.map((item) => ({value: item.id,label: item.value,}))}/></Form.Item><Form.Itemname="roleId"label="角色"rules={[{ required: true, message: '请选择角色' }]}><SelectshowSearchplaceholder="请选择角色"optionFilterProp="label"onChange={handleRoleChange}options={props.roleList.map((item) => ({value: item.id,label: item.roleName,}))}/></Form.Item></Form>)
})export default UserForm

实现一个过滤地区的功能

这个过滤是table组件自带的功能

筛选主要控制的是onFilter属性

import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch, Form, Menu } from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'const { confirm } = Modal
function UserList() {const [dataSource, setdataSource] = useState([])const [isAddVisible, setisAddVisible] = useState(false)const [roleList, setroleList] = useState([])const [regionList, setregionList] = useState([])const [isUpdateVisible, setisUpdateVisible] = useState(false)const [isUpdateDisabled, setisUpdateDisabled] = useState(false)const [form] = Form.useForm() //创建antd的form实例const [current,setCurrent] = useState(null)const updateForm = useRef(null)const addForm = useRef(null)useEffect(() => {axios.get('http://localhost:3000/users?_expand=role').then((res) => {// console.log(res.data);const list = res.datasetdataSource(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/regions').then((res) => {// console.log(res.data);const list = res.datasetregionList(list)})}, [])useEffect(() => {axios.get('http://localhost:3000/roles').then((res) => {// console.log(res.data);const list = res.datasetroleList(list)})}, [])const deleteMethod = (record) => {// console.log(record);//页面状态+后端setdataSource(dataSource.filter((item) => item.id !== record.id))axios.delete(`http://localhost:3000/users/${record.id}`)}const confirmMethod = (record) => {confirm({title: '确定要删除这个角色吗?',icon: <ExclamationCircleOutlined />,onOk() {deleteMethod(record)},onCancel() {console.log('取消删除')},})}const handleChange = (item) => {// console.log(item)item.roleState = !item.roleStatesetdataSource([...dataSource])axios.patch(`http://localhost:3000/users/${item.id}`, {roleState: item.roleState,})}const columns = [{title: '区域',dataIndex: 'region',filters:[...regionList.map((item) => ({text: item.value,value: item.value,})),{text: '全球',value: '全球',}],onFilter: (value, item) =>{if(value === '全球') {return item.region === ""}return item.region===value}, render: (region) => {return <b>{region === '' ? '全球' : region}</b>},},{title: '角色名称',dataIndex: 'role',render: (role) => {return role?.roleName},},{title: '用户名',dataIndex: 'username',},{title: '用户状态',dataIndex: 'roleState',render: (roleState, item) => {return (<Switchchecked={roleState}disabled={item.default}onChange={() => handleChange(item)}></Switch>)},},{title: '操作',render: (record) => {return (<div><Buttontype="primary"shape="circle"icon={<EditOutlined />}disabled={record.default}onClick={() => handleUpdate(record)}/><Buttondangertype="primary"shape="circle"icon={<DeleteOutlined />}disabled={record.default}onClick={() => confirmMethod(record)}/></div>)},},]const addFormOk = () => {addForm.current.validateFields().then((value) => {// console.log(value)setOpen(false)addForm.current.resetFields()//post到后端生成id,再设置dataSource,方便删除和更新// 修正: 确保 `region` 存储的是字符串,而不是 id// const selectedRegion = regionList.find(item => item.id === value.region)?.value || "";// 添加用户的代码逻辑const selectedRegion =regionList.find((item) => item.id === value.region)?.value || ''axios.post(`http://localhost:3000/users`, {...value,region: selectedRegion, // 存储的是区域的名称(如"华东")})// 获取所选角色的名称const selectedRole =roleList.find((item) => item.id === value.roleId)?.roleName || ''axios.post(`http://localhost:3000/users`, {...value,roleState: true,default: false,region: selectedRegion, // 修正 `region` 的值roleName: selectedRole, // 修正 `roleName` 的值}).then((res) => {console.log(res.data)setdataSource([...dataSource,{...res.data,role: roleList.filter((item) => item.id === value.roleId)[0],},])})}).catch((errInfo) => {console.log(errInfo)})}const [isUpdate, setisUpdate] = useState(false)const [updateform] = Form.useForm() //创建antd的updateform实例const handleUpdate = (item) => {setisUpdateVisible(true);setisUpdateDisabled(item.default);setTimeout(() => {//保证超级管理员的区域禁用if(item.roleId === 1) {setisUpdateDisabled(true)} else {setisUpdateDisabled(false)}updateform.setFieldsValue({username: item.username,password: item.password, // 确保密码字段被正确设置region: item.region,roleId: item.role?.id,});}, 100); // 增加一定的延迟确保 Modal 已渲染setCurrent(item)}const [open, setOpen] = useState(false)const updateFormOk = () => {updateform.validateFields().then((value) => {setisUpdateVisible(false);const selectedRegion = regionList.find(region => region.id === value.region)?.value || '';setdataSource(dataSource.map((item) => {if (item.id === current.id) {return {...item,...value,region: selectedRegion, // 将区域 ID 转换为区域名称role: roleList.filter((data) => data.id === value.roleId)[0],}}return item;}));// 同步后端数据axios.patch(`http://localhost:3000/users/${current.id}`, {...value,region: selectedRegion, // 确保后端也存储区域名称});});}return (<div><Button type="primary" onClick={() => setOpen(true)}>添加用户</Button><TabledataSource={dataSource}columns={columns}pagination={{pageSize: 5,}}>rowKey = {(item) => item.id}</Table><Modalopen={open}title="添加用户"okText="确定"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => setOpen(false)}onOk={() => addFormOk()}destroyOnClosemodalRender={(dom) => <Form layout="vertical">{dom}</Form>}><UserFormregionList={regionList}roleList={roleList}ref={addForm}></UserForm></Modal>{/* 更新  */}<Modalopen={isUpdateVisible}title="更新用户"okText="更新"cancelText="取消"okButtonProps={{ autoFocus: true, htmlType: 'submit' }}onCancel={() => {setisUpdateVisible(false)setisUpdateDisabled(!isUpdateDisabled)}}onOk={() => updateFormOk()}destroyOnClosemodalRender={(dom) => (<Form layout="vertical" form={updateform}>{/* //将form实例传递给Form组件 */}{dom}</Form>)}><UserFormregionList={regionList}roleList={roleList}form={updateform}isUpdateDisabled={isUpdateDisabled}></UserForm></Modal></div>)
}export default UserList

至此用户阶段的增删改查全部完成

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/74103.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

吾爱破解安卓逆向学习笔记(4p)

学习目标&#xff0c;了解安卓四大组件&#xff0c;activity生命周期&#xff0c;同时了解去除部分广告和更新提示。 广告类型 1.启动页广告 2.更新广告 3.横幅广告 安卓四大组件 组件描述Activity(活动)在应用中的一个Activity可以用来表示一个界面&#xff0c;意思可以…

【目标检测】【深度学习】【Pytorch版本】YOLOV1模型算法详解

【目标检测】【深度学习】【Pytorch版本】YOLOV1模型算法详解 文章目录 【目标检测】【深度学习】【Pytorch版本】YOLOV1模型算法详解前言YOLOV1的模型结构YOLOV1模型的基本执行流程YOLOV1模型的网络参数YOLOV1模型的训练方式 YOLOV1的核心思想前向传播阶段网格单元(grid cell)…

Vue项目中Vuex在util引入,断点存在default

示例代码 // src/store/index.js import Vue from vue; import Vuex from vuex; ……Vue.use(Vuex); export default new Vuex.Store({…… })// src/utils/index.js import store from /store // 导入默认导出的 store export async function getDict() {store.state.userInf…

FALL靶机渗透实战:从信息收集到特权升级的完整链分析

1.下载靶机&#xff0c;并在虚拟机中打开 2.用kali来确定该靶机的IP kali的IP&#xff1a;192.168.139.152 arp-scan -l 3.扫描端口 nmap -O 192.168.139.172 4.扫目录 gobuster dir -u http://192.168.139.172 -x php,txt,html -w /usr/share/dirbuster/wordlists/directo…

谈谈常见的数据结构(如数组、链表、栈、队列、哈希表、树、图)及其应用场景

一、数组&#xff08;Array&#xff09; 定义&#xff1a;连续存储相同类型数据的线性结构&#xff0c;支持随机访问。 应用场景&#xff1a;列表渲染、数据缓存、算法处理 代码示例&#xff1a; // 数组基本操作 const arr [1, 2, 3, 4]; arr.push(5); // O(1) 平均时间复杂…

Kafka 的高可用性

Kafka 的高可用性主要通过副本机制、ISR&#xff08;In-Sync Replicas&#xff09;列表和控制器 Broker 来实现。这些机制共同确保了 Kafka 集群在部分节点故障时仍然可以正常运行&#xff0c;数据不会丢失&#xff0c;并且服务不会中断。 1. 副本机制 Kafka 的副本机制是其高…

力扣HOT100之矩阵:54. 螺旋矩阵

这道题之前在代码随想录里刷过类似的&#xff0c;还有印象&#xff0c;我就按照当初代码随想录的思路做了一下&#xff0c;结果怎么都做不对&#xff0c;因为按照代码随想录的边界条件设置&#xff0c;当行数和列数都为奇数时&#xff0c;最后一个元素无法被添加到数组中&#…

快速构建个人本地知识库管理系统与实现RAG问答

文章目录 摘要一、RAG 和知识库简介1、RAG2、知识库 二、 工作流程三、系统架构设计文件结构知识库构建模块RAG 模块用户交互模块 四、技术实现细节五、系统使用案例结论未来改进方向致谢 摘要 在当今信息爆炸的时代&#xff0c;快速准确地获取知识变得尤为重要。本地 RAG&…

使用DeepSeek API进行情感分析:超简单

文章目录 1. 引言1.1 情感分析概述1.2 为什么选择DeepSeek API1.3 本文目标 2. 技术方案对比2.1 传统情感分析方法2.2 基于LLM的方法DeepSeek API优势 3. DeepSeek 情感分析实战3.1 Few-shot Learning方法3.2 完整的DeepSeek API调用示例3.3 案例演示 4. DeepSeek开发情感分析工…

设置网站主题色color-scheme

color-scheme color-scheme CSS 属性允许元素指示它可以舒适地呈现哪些颜色方案。 操作系统颜色方案的常见选择为“亮色”和“暗色”&#xff0c;或“日间模式”和“夜间模式”。当用户选择其中一种颜色方案时&#xff0c;操作系统会对用户界面进行调整&#xff0c;包括表单控件…

Muduo网络库实现 [三] - Socket模块

目录 设计思路 类的设计 模块的实现 基础模块 特殊模块 集成模块 主函数 主函数实现 主函数测试 疑惑点 设计思路 Socket模块主要是对套接字的基础操作进行封装&#xff0c;简化我们对套接字的操作&#xff0c;不需要调用C的原生接口&#xff0c;而是以面向对象的…

优选算法的巧思之径:模拟专题

专栏&#xff1a;算法的魔法世界 个人主页&#xff1a;手握风云 目录 一、模拟 二、例题讲解 2.1. 替换所有的问号 2.2. 提莫攻击 2.3. Z字形变换 2.4. 外观数列 2.5. 数青蛙 一、模拟 模拟算法说简单点就是照葫芦画瓢&#xff0c;现在草稿纸上模拟一遍算法过程&#xf…

贪心算法(13)(java)合并区间

题目&#xff1a; 以数组 intervals 表示若干个区间的集合&#xff0c;其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间&#xff0c;并返回 一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中的所有区间 。 示例 1&#xff1a; 输入&#xff…

A股复权计算_权息数据整理

目录 前置&#xff1a; 步骤&#xff1a; 1 以通达信为参照 2 从优矿获取所需数据 2.1 股票配股信息 2.2 股票分红信息 2.3 股票拆股信息 3 合并数据&#xff0c;制成权息数据表 权息数据截止20250329.7z 视频 前置&#xff1a; 1 本系列将以 “A股复权计算_” 开头…

学习笔记—数据结构—二叉树(链式)

目录 二叉树&#xff08;链式&#xff09; 概念 结构 初始化 遍历 前序遍历 中序遍历 后序遍历 层序遍历 结点个数 叶子结点个数 第k层结点个数 深度/高度 查找值为x的结点 销毁 判断是否为完整二叉树 总结 头文件Tree.h Tree.c 测试文件test.c 补充文件Qu…

Open GL ES ->GLSurfaceView在正交投影下的图片旋转、缩放、位移

XML文件 <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:o…

Day78 | 灵神 | 反转链表 两两交换链表中的节点

Day78 | 灵神 | 反转链表 两两交换链表中的节点 24.两两交换链表中的节点 24. 两两交换链表中的节点 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 这道题就是下面这道题的k2的情况 25. K 个一组翻转链表 - 力扣&#xff08;LeetCode&#xff09; 基本思路和…

滤波---卡尔曼滤波

卡尔曼滤波概览 一、定义 卡尔曼滤波是一种基于线性系统和高斯噪声假设的递归最优状态估计算法。其核心目标是通过融合系统模型预测值与传感器测量值&#xff0c;在噪声环境中实时估计系统的动态状态&#xff08;如位置、速度、加速度等&#xff09;。 数学基础&#xff1a; …

23种设计模式-结构型模式-桥接器

文章目录 简介问题解决方案示例总结 简介 桥接器是一种结构型设计模式&#xff0c;可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构&#xff0c;从而能在开发时分别使用。 问题 假如你有一个几何形状Shape类&#xff0c;它有两个子类&#xff1a;圆形C…

手工排查后门木马的常用姿势

声明&#xff01;本文章所有的工具分享仅仅只是供大家学习交流为主&#xff0c;切勿用于非法用途&#xff0c;如有任何触犯法律的行为&#xff0c;均与本人及团队无关&#xff01;&#xff01;&#xff01; 1. 检查异常文件 &#xff08;1&#xff09;查找最近修改的文件 # 查…