草庐IT

#yyds干货盘点# react笔记之学习之完成删除功能

前端歌谣 2023-03-28 原文

前言

我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷

代码案例LogItem.js

import React, { useState, useEffect, useCallback, memo } from 'react';
import {
Modal,
Input,
message,
Form,
Select,
Table,
Button,
Row,
Col,
Card,
DatePicker,
Cascader,
Tabs,
Typography, InputNumber
} from 'antd';
import { Menu } from '../service';
import {
useQueryOrderDetailMutation, useManufactureAddMutation
} from '@/restapi/service/order/order'
import {
useLazyQueryBaseCustomerQuery,
useLazyQueryCategoryListQuery, useLazyQueryColorTypeListQuery, useLazyQuerySizeTypeListQuery,
useLazyQueryStyleDataListQuery
} from "@/restapi/service/commonselect/tablerestapi";
import styles from "./indexOrder.module.less";
import { SingleValueType } from 'rc-cascader/lib/Cascader';
import { useQueryRegionListMutation } from "@/restapi/service/factory/factory";
import moment from "moment";
import { useNavigate } from "react-router";
const { Option } = Select
const { TabPane } = Tabs;
interface AddOrEditMenuFormProps {
id?: number;
}
export interface AddOrEditMenuProps {
visible: boolean;
menu: Menu | null;
onClose: () => void;
onConfirm: (obj: any) => void;
list: any[]
}
type ListItemType = {
code?: string | number;
id?: string;
name?: string;
}
interface Option {
id?: string;
name?: string;
children?: Option[];
}
const isEditing = (record: any) => {
return record.editable;
};
type ValueType = SingleValueType | SingleValueType[]
const AddScModel: React.FC<any> = (props) => {
const { addData } = props
const navigate = useNavigate()
const [form] = Form.useForm();
const [formKuan] = Form.useForm();
const [data, setData] = useState<any>([]); //存放表格内容
const [disFlag, setDisFlag] = useState<boolean>(false)
const [region, setRegion] = useState<Array<Option>>()
const [regionData, setRegionData] = useState<ValueType>()
const [customeList, setCustomList] = useState<ListItemType[]>([])
const [styleList, setStyleList] = useState<Array<ListItemType>>([])
const [styleList2, setStyleList2] = useState<Array<ListItemType>>([])
//存储数据
const [styleList3, setStyleList3] = useState<Array<ListItemType>>([])
const [sizeList, setSizeList] = useState<ListItemType[]>([])
const [getStyle, setGetStyle] = useState<any>("");
const [queryBaseCustomer] = useLazyQueryBaseCustomerQuery();
const [queryRegionList] = useQueryRegionListMutation()
const [queryCategoryList] = useLazyQueryCategoryListQuery()
const [queryColorList] = useLazyQueryColorTypeListQuery()
const [querySizeList] = useLazyQuerySizeTypeListQuery()
const [queryOrderDetailList] = useQueryOrderDetailMutation()
const [queryStyleDataList] = useLazyQueryStyleDataListQuery()
const [manufactureAdd] = useManufactureAddMutation()
const [activeKey, setActiveKey] = useState<string>();
const [editingKey, setEditingKey] = useState("");
const columnsTab = [
{
title: '颜色',
dataIndex: 'colorId',
width: 300,
editable: false,
componentType: 'select',
message: '请输入颜色',
render: (text: any) => {
return getColor(text)
}
},
{
title: '尺码',
editable: false,
dataIndex: 'sizeId',
width: 300,
componentType: 'select',
message: '请输入尺码',
render: (text: any) => {
return getSize(text)
}
},
{
title: '合同数量',
editable: false,
dataIndex: 'ordCount',
width: 300,
componentType: 'input',
message: '请输入合同数量'
},
{
title: '生产数量',
editable: true,
dataIndex: 'count',
width: 300,
componentType: 'input',
message: '请输入生产数量'
},
{
title: '操作',
dataIndex: '',
width: 300,
fixed: 'right',
render: (text: any, record: any, index: number) => {
// 判断是否进入编辑状态
const editable = isEditing(record);
return editable ? (
<span>
<a
onClick={() => save(record.id, record)}
style={{
marginRight: 8
}}
>
保存
</a>
<a onClick={() => cancel(record.id)}>取消</a>
</span>
) : (
<div>
<Typography.Link
disabled={editingKey !== ""}
onClick={() => edit(record)}
>
编辑
</Typography.Link>
<Button type="link" onClick={() => delInfo(record, index)}>删除</Button>
</div>

);
}
}

]
//行编辑
const getColor = (value: any) => {
let text: any = ''
styleList.forEach((item) => {
if (value == item.id) {
text = item.name
}
})
return text
}
const getSize = (value: any) => {
let text: any = ''
sizeList.forEach((item) => {
if (value == item.id) {
text = item.name
}
})
return text
}
const delInfo = useCallback((record: any, index: number) => {
console.log(record, index, "data")
const list = [...data]
console.log(list)
list.splice(index, 1)
setData(list)
}, [data])
const save = async (key: any, record: any) => {
try {
const row: any = await formKuan.validateFields();
if (record.ordCount < row.count) {
message.warning('生产数量不能大于合同数量,请重新输入!')
return false
}
const newData = [...data];
const index = newData.findIndex((item: any) => key === item.id);
if (index > -1) {
const item: any = newData[index];
item.editable = false;
newData.splice(index, 1, { ...item, ...row });
setData(newData);
setEditingKey("");
} else {
newData.push(row);
setData(newData);
setEditingKey("");
}
} catch (errInfo) {
console.log("保存失败", errInfo);
}
};
const edit = async (record: any) => {
formKuan.setFieldsValue({
editable: true,
...record
});
setEditingKey(record.id);
//切换成编辑状态
const newData: any = [...data];
const index = newData.findIndex((item: any) => record.id === item.id);
if (index > -1) {
const item = { ...newData[index], editable: true };
newData.splice(index, 1, { ...item });
setData(newData)
}
};
const cancel = (id: any) => {
const newData = [...data];
const index = newData.findIndex((item: any) => id === item.id);
if (index > -1) {
const item: any = newData[index];
item.editable = false;
newData.splice(index, 1, { ...item });
setData(newData);
setEditingKey("");
}
};
const EditableCell = ({
editing,
dataIndex,
title,
inputType,
record,
index,
children,
...restProps
}: {
editing: any,
dataIndex: any,
title: any,
inputType: any,
record: any,
index: any,
children: any
}) => {
const inputNode = <InputNumber min={1} style={{ width: "300px" }} autoComplete="off" />

const selectNode = dataIndex == 'sizeId' ? <Select
style={{ width: "300px" }}
placeholder="请选择尺寸"
optionFilterProp="children"
>
{sizeList && sizeList.map((item: any) => (
<Option value={item.id}>{item.name}</Option>
))}
</Select> : <Select
style={{ width: "300px" }}
placeholder="请选择颜色"
optionFilterProp="children"
>
{styleList && styleList.map((item: any) => (
<Option value={item.id}>{item.name}</Option>
))}
</Select>
return (
<td {...restProps}>
{editing ? (
<Form.Item
name={dataIndex}
style={{
margin: 0
}}
rules={[
{
required: false,
message: `请输入${title}!`
}
]}
>
{inputType == 'input' ? inputNode : selectNode}
</Form.Item>
) : (
children
)}
</td>
);
};
// 依据是否可编辑返回不同元素
const mergedColumns = columnsTab.map((col: any) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record: any) => ({
record,
inputType: col.componentType,
dataIndex: col.dataIndex,
title: col.title,
editing: isEditing(record)
})
};
});
const onOk = () => {
if (data.length == 0) {
message.warning('请添加款式!')
} else {
form.validateFields().then(res => {
console.log(res, "res")
const values = res
const info: any = {
...values,
};
console.log(info, "info")
if (info.id) {
} else {
info.orderId = form.getFieldValue("id")
info.itemList = data.filter((item: any) => {
return item.styleId === getStyle
})
manufactureAdd(info)
.unwrap()
.then((response: any) => {
if (response.code === 200) {
// navigate("/productionOrder")
message.success('添加成功')

}
});
}
});
}
}

const onClose = () => {
form.resetFields()
props.onClose()
};
useEffect(() => {
querySizeList("t_sys_institution")
.unwrap()
.then((response: any) => {
console.log(response, "response")
let arr: ListItemType[] = []
response.data && response.data.map((item: any) => {
arr.push({ code: item.code, id: item.id, name: item.name })
})
console.log(arr, "arr")
setSizeList(arr)
});
}, [])
//查看款式得接口
useEffect(() => {
queryColorList("")
.unwrap()
.then((response: any) => {
if (response.code === 200) {
let arr: ListItemType[] = []
response.data && response.data.map((item: any) => {
arr.push({ code: item.code, id: item.id, name: item.name })
})
setStyleList(arr)
}
});
}, []);

//查看省市区的接口
useEffect(() => {
queryRegionList("/style/type/getComboBox")
.unwrap()
.then((response: any) => {
if (response.code === 200) {
setRegion(response.data)
}
});
}, []);
//查看款式
useEffect(() => {
queryBaseCustomer("t_sales_order")
.unwrap()
.then((response: any) => {
console.log(response, "response")
let arr: ListItemType[] = []
response.data && response.data.map((item: any) => {
arr.push({ code: item.code, id: item.id, name: item.name })
})
setCustomList(arr)
});
}, [])
const setFormValue = (value: any) => {
form.setFieldsValue({
...value,
areaAll: [value.province, value.city, value.area]
})
}
const queryDetail = (obj: any) => {
queryOrderDetailList({ orderId: obj.id })
.unwrap()
.then((response: any) => {
if (response.code == 200) {
let arr: ListItemType[] = []
const list: any = [...response.data.typeList]
list && list.map((item: any) => {
arr.push({ code: item.code, id: item.styleId, name: item.styleName })
})
setStyleList2(arr)
setStyleList3(arr)
const newDate = [...response.data.itemList]
setData(
newDate.map((item: any) => {
return { ...item, editable: false, ordCount: item.count }
})
)
setActiveKey(arr[0].id)
}
})
;
}

const makeStyle = (value: any) => {
setGetStyle(value)
}
const remove = (targetKey: string) => {
let newActiveKey = activeKey;
let lastIndex = -1;
styleList2.forEach((item, i) => {
if (item.id == targetKey) {
lastIndex = i - 1;
}
});
console.log(lastIndex, "lastIndex")
const newPanes = styleList2.filter(item => item.id != targetKey);
if (newPanes.length > 0) {
setStyleList2(newPanes);
setActiveKey(newPanes[0].id);
} else {
setStyleList2([]);
setActiveKey("");
}
// console.log([...data].filter((item: any) => {
// return targetKey != item.styleId
// }), targetKey)
// setData([...data].filter((item: any) => {
// return targetKey != item.styleId
// }))
// console.log(newPanes,"newPanes")
// setStyleList2(newPanes);
// setActiveKey(newActiveKey);
};


const onChange = (newActiveKey: string) => {
console.log(data, "data")
setActiveKey(newActiveKey);
};
const onEdit = (targetKey: any, action: 'add' | 'remove') => {
if (action === 'add') {
// add();
} else {
remove(targetKey);
}
};

useEffect(() => {
const dataObj = { ...props.addData }
dataObj.planDate = moment(dataObj.planDate)
setFormValue(dataObj)
queryDetail(props.addData)
console.log(props)
}, [props.addData])
const handleRecover = () => {
setStyleList2(styleList3)
setActiveKey(styleList3[0].id)
}
console.log(addData,"addDataaddDataaddData")
return (
<div>
<div className={styles['fontFlag']}>
基本信息
</div>
<Card style={{ marginTop: "20px" }}>
<Row style={{ marginTop: "20px" }} gutter={24}>
<Col span={6}>
客户名称:{addData?.customerName}
</Col>
<Col span={6}>
订单号:{addData?.orderCode}
</Col>
<Col span={6}>
合同号:{addData?.contractNumber}
</Col>
{/* <Col span={6}>
交货日期:{croppData?.plan_date}
</Col> */}
{/* <Col span={6}>
款式名称:{croppData?.style_name}
</Col> */}
{/* <Col span={6}>
款式编码:{croppData?.style_number}
</Col> */}
</Row>
</Card>

{/* <Card className={styles['marginTen']}>
<Form
disabled
form={form}
labelCol={{
sm: { span: 5 },
}}
wrapperCol={{
sm: { span: 16 },
}}
>
<Row gutter={24}>
<Col span={7}>
<Form.Item
label="客户名称"
name="customerId"
rules={[{ required: false, message: '请输入客户名称' }]}
>
<Select
showSearch
style={{ width: 200 }}
placeholder="请输入客户名称"
optionFilterProp="children"
>
{customeList && customeList.map((item: any) => (
<Option value={item.id}>{item.name}</Option>
))}
</Select>
</Form.Item>
</Col>

<Col span={7}>
<Form.Item
label="合同号"
name="contractNumber"
rules={[{ required: false, message: '请输入合同号' }]}
>
<Input />
</Form.Item>
</Col>
<Col span={7}>
<Form.Item
label="订单编号"
name="orderCode"
rules={[{ required: false, message: '请输入订单编号' }]}
>
<Input />
</Form.Item>
</Col>
</Row>

</Form>
</Card> */}

<div className={styles['kuanFlag']}>
<div>
款式信息
</div>
</div>
<div className={styles['kuanFlag']}>
<Button onClick={handleRecover} type='primary'>恢复</Button>
</div>
<div className={styles['marginTopHeight']}>
{/* <Select
style={{ width: 200 }}
placeholder="请选择所属款式"
optionFilterProp="children"
key={getStyle}
defaultValue={getStyle}
onChange={makeStyle}
>
{styleList2 && styleList2.map((item: any) => (
<Option value={item.id}>{item.name}</Option>
))}
</Select> */}
<Tabs
hideAdd
onChange={onChange}
activeKey={activeKey}
type="editable-card"
onEdit={onEdit}
>
{styleList2 && styleList2.map((pane, index) => (
<TabPane closable tab={pane.name} key={pane.id}>
</TabPane>
))}

</Tabs>
</div>
<div className={styles['marginBack']}>
<Form form={formKuan} component={false}>
<Table
className="user-table"
rowKey="id"
components={{
body: {
cell: EditableCell
}
}}
dataSource={data.filter((item: any) => item.styleId == activeKey)}
columns={mergedColumns}
pagination={false}
summary={data => {
let totalCount = 0;
data.forEach((item: any) => {
if (item.styleId === activeKey) {
totalCount += parseInt(item.count);
}
});
return (
<>
<Table.Summary.Row>
<Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
<Table.Summary.Cell index={1}>
</Table.Summary.Cell>
<Table.Summary.Cell index={2}>
</Table.Summary.Cell>
<Table.Summary.Cell index={3}>
<span>{totalCount}</span>
</Table.Summary.Cell>
</Table.Summary.Row>
</>
);
}}
/>
</Form>
</div>
<Card>
<div className={styles['bottomBtn']}>
<Button onClick={onClose} className={styles['kuanButtonContent']}>取消</Button>
<Button type={"primary"} className={styles['kuanButtonContent']} onClick={onOk}>保存</Button>
</div>
</Card>
</div>
);
}

export default memo(AddScModel);

有关#yyds干货盘点# react笔记之学习之完成删除功能的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  3. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  4. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  5. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

  6. ruby-on-rails - 标准化文件名的字符串,删除重音和特殊字符 - 2

    我正在尝试找到一种方法来规范化字符串以将其作为文件名传递。到目前为止我有这个:my_string.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.gsub(/[^a-z]/,'_')但第一个问题:-字符。我猜这个方法还有更多问题。我不控制名称,名称字符串可以有重音符、空格和特殊字符。我想删除所有这些,用相应的字母('é'=>'e')替换重音符号,并将其余的替换为'_'字符。名字是这样的:“Prélèvements-常规”“健康证”...我希望它们像一个没有空格/特殊字符的文件名:“prelevements_routin

  7. LC滤波器设计学习笔记(一)滤波电路入门 - 2

    目录前言滤波电路科普主要分类实际情况单位的概念常用评价参数函数型滤波器简单分析滤波电路构成低通滤波器RC低通滤波器RL低通滤波器高通滤波器RC高通滤波器RL高通滤波器部分摘自《LC滤波器设计与制作》,侵权删。前言最近需要学习放大电路和滤波电路,但是由于只在之前做音乐频谱分析仪的时候简单了解过一点点运放,所以也是相当从零开始学习了。滤波电路科普主要分类滤波器:主要是从不同频率的成分中提取出特定频率的信号。有源滤波器:由RC元件与运算放大器组成的滤波器。可滤除某一次或多次谐波,最普通易于采用的无源滤波器结构是将电感与电容串联,可对主要次谐波(3、5、7)构成低阻抗旁路。无源滤波器:无源滤波器,又称

  8. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  9. ruby-on-rails - 为什么在 Rails 5.1.1 中删除了 session 存储初始化程序 - 2

    我去了这个website查看Rails5.0.0和Rails5.1.1之间的区别为什么5.1.1不再包含:config/initializers/session_store.rb?谢谢 最佳答案 这是删除它的提交:Setupdefaultsessionstoreinternally,nolongerthroughanapplicationinitializer总而言之,新应用没有该初始化器,session存储默认设置为cookie存储。即与在该初始值设定项的生成版本中指定的值相同。 关于

  10. ruby - 如果它是标点符号,我怎么能从字符串中删除最后一个字符,在 ruby​​ 中? - 2

    啊,正则表达式有点困惑。我正在尝试删除字符串末尾所有可能的标点符号:ifstr[str.length-1]=='?'||str[str.length-1]=='.'||str[str.length-1]=='!'orstr[str.length-1]==','||str[str.length-1]==';'str.chomp!end我相信有更好的方法来做到这一点。有什么指点吗? 最佳答案 str.sub!(/[?.!,;]?$/,'')[?.!,;]-字符类。匹配这5个字符中的任何一个(注意,。在字符类中并不特殊)?-前一个字符或组

随机推荐