Здравствуйте. У меня реализована возможность с помощью стрелок менять строки местами в таблице. Но при открытии формы для редактирования данных строке, туда подставляются данные не той строки. Подскажите пожалуйста как это исправить?
Вывод строк таблицы в map:
import React from 'react';
import TechStore from "../../../../../TechStore";
import ButtonEditOperation from "../ButtonEditOperation/ButtonEditOperation";
import ButtonAddContentOperation from "../ButtonAddContentOperation/ButtonAddContentOperation";
import ButtonDeleteOperation from "../ButtonDeleteOperation/ButtonDeleteOperation";
import OutputOperation from "./OutputOperation/OutputOperation";
import {observer} from "mobx-react";
const OutputOperations = observer(({item, index}) => {
const {dataTable} = TechStore
const handleClick = (index, item) => (
() => {
dataTable.forEach((operation) => {
operation["clicked"] = false
})
item["clicked"] = true
dataTable[index] = item
console.log('clickTR')
}
)
return (
<tr
style={dataTable[index]["clicked"] ? {
backgroundColor: "#E4F2FE"
} : {}}
onClick={handleClick(index, item)}
>
<OutputOperation
item={item}
index={index}
/>
<td>
<div className="groupButton">
<ButtonEditOperation index={index} item={item}/>
<ButtonAddContentOperation index={index}/>
<ButtonDeleteOperation index={index} item={item}/>
</div>
</td>
</tr>
)
})
export default OutputOperations
Логика открытия формы и валидация:
import React, {useState} from 'react'
import '../../OperationTable.css'
import {
Button,
Dialog,
DialogActions,
DialogContent,
} from "@mui/material"
import EditIcon from '@mui/icons-material/Edit'
import {observer} from "mobx-react"
import OutputOperationTextField from "./OutputOperationTextField/OutputOperationTextField"
import OutputOperationCheckbox from "./OutputOperationCheckbox/OutputOperationCheckbox"
import TechStore from "../../../../../TechStore"
import HeaderModalWindow from "../../../HeaderModalWindow"
import {toJS} from "mobx";
const ButtonEditOperation = observer(({index, item}) => {
const {dataTable} = TechStore
const [operationItem, setOperationItem] = useState(item)
const [open, setOpen] = useState(false)
//-------------------------initialValidation-------------------
let copyItem = JSON.parse(JSON.stringify(item))
const fieldsCopyItemDeleted = ['id', 'OO', 'OTK', 'PZ', 'KPS', 'transition', 'equipment', 'adaptation', 'tool', 'clicked']
for (const key in copyItem) {
if (fieldsCopyItemDeleted.includes(key)) {
delete copyItem[key]
} else {
copyItem[key] = false
}
}
const [isValid, setIsValid] = useState(copyItem)
//-------------------------initialValidation-------------------
const handleClickOpen = (event) => {
event.stopPropagation()
console.log('clickEDIT')
setOpen(true)
}
const handleClose = () => {
setOpen(false)
}
const handleInputAndCheckboxChange = (event) => {
const {name, type} = event.target
const value = (type === 'checkbox') ? event.target.checked : event.target.value
setOperationItem({...operationItem, [name]: value})
}
const handleSubmit = (event) => {
event.preventDefault()
const letterCheck = /^[а-яА-Я][а-я А-Я]+[а-яА-Я]$/
const numberCheck = /^[0-9]+$/
let copyIsValid = JSON.parse(JSON.stringify(isValid))
for (const key in isValid) {
if (key === 'nameOperation') {
letterCheck.test(operationItem[key]) ? copyIsValid[key] = false : copyIsValid[key] = true
} else {
numberCheck.test(operationItem[key]) ? copyIsValid[key] = false : copyIsValid[key] = true
}
}
setIsValid(copyIsValid)
const valuesIsValid = Object.values(copyIsValid)
if (!valuesIsValid.includes(true)) {
dataTable[index] = operationItem
setOpen(false)
}
}
return (
<>
<Button
variant="text"
onClick={handleClickOpen}
>
<EditIcon fontSize="small"/>
</Button>
<Dialog
open={open}
onClose={handleClose}
className="buttonEditItemOperationModalWindow"
>
<HeaderModalWindow header="Редактировать данные операции" handleClose={handleClose}/>
<DialogContent dividers>
<form method="POST" onSubmit={handleSubmit}>
<OutputOperationTextField
operationItem={operationItem}
handleInputAndCheckboxChange={handleInputAndCheckboxChange}
nameFieldFirstInput="numberOperation"
nameFieldSecondInput="nameOperation"
nameFieldThirdInput="level"
nameFieldFourthInput="workshop"
nameFieldFifthInput="area"
isValid={isValid}
/>
<OutputOperationCheckbox
operationItem={operationItem}
handleInputAndCheckboxChange={handleInputAndCheckboxChange}
nameFieldFirstInput="OO"
nameFieldSecondInput="OTK"
nameFieldThirdInput="PZ"
nameFieldFourthInput="KPS"
/>
<DialogActions>
<Button
type="submit"
variant="contained"
color="success"
>
Сохранить
</Button>
</DialogActions>
</form>
</DialogContent>
</Dialog>
</>
)
})
export default ButtonEditOperation
Логика кнопок для перемещения строк вверх и вниз:
import React from 'react'
import {Button} from "@mui/material";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import TechStore from "../../TechStore";
import {observer} from "mobx-react";
import {toJS} from "mobx";
const RowMoveUpAndDown = observer(() => {
const {dataTable, radioButtons} = TechStore
let index = 0
dataTable.forEach((operation, indexOperation) => {
if (operation['clicked']) {
index = indexOperation
}
})
const buttonStyle = {
but1: {
minWidth: '30px',
padding: 0,
marginRight: '5px'
},
but2: {
minWidth: '30px',
padding: 0,
}
}
const handleClickRowUp = () => {
let strPrev
if (index === 0) {
strPrev = dataTable[index]
dataTable.splice(index, 1)
dataTable.splice((dataTable.length), 0, strPrev)
} else {
strPrev = dataTable[index - 1]
dataTable[index - 1] = dataTable[index]
dataTable[index] = strPrev
}
dataTable.forEach((operation) => {
operation["clicked"] = false
})
if (index === 0) {
dataTable[dataTable.length - 1]["clicked"] = true
} else {
dataTable[index - 1]["clicked"] = true
}
}
const handleClickRowDown = () => {
let strPrev
if (index === (dataTable.length - 1)) {
strPrev = dataTable[dataTable.length - 1]
dataTable.splice((dataTable.length - 1), 1)
dataTable.splice(0, 0, strPrev)
} else {
strPrev = dataTable[index + 1]
dataTable[index + 1] = dataTable[index]
dataTable[index] = strPrev
}
dataTable.forEach((operation) => {
operation["clicked"] = false
})
if (index === (dataTable.length - 1)) {
dataTable[0]["clicked"] = true
} else {
dataTable[index + 1]["clicked"] = true
}
}
return (
<>
{(radioButtons["content"] || radioButtons["norm"]) ? (
<>
<Button
disabled
variant="contained"
sx={buttonStyle.but1}
className="buttonStyle"
onClick={handleClickRowUp}
>
<ExpandLessIcon/>
</Button>
<Button
disabled
variant="contained"
sx={buttonStyle.but2}
onClick={handleClickRowDown}
>
<ExpandMoreIcon/>
</Button>
</>
) : (
<>
<Button
variant="contained"
sx={buttonStyle.but1}
className="buttonStyle"
onClick={handleClickRowUp}
>
<ExpandLessIcon/>
</Button>
<Button
variant="contained"
sx={buttonStyle.but2}
onClick={handleClickRowDown}
>
<ExpandMoreIcon/>
</Button>
</>
)}
</>
)
})
export default RowMoveUpAndDown
Исходная таблица и форма с данными:
После перемещения данные не совпадают: