Anonymous
Как избежать ненужных повторных ресурсов в React, работая с формами в нескольких вкладках?
Сообщение
Anonymous » 08 апр 2025, 23:06
Я создал компонент с тремя вкладками. Каждая вкладка имеет форму. Я ввожу детали в первой форме и перехожу во вторую форму. После этого я снова возвращаюсь к первой форме, и форма вернулась к начальному состоянию. Как этого избежать? < /P>
Код: Выделить всё
"use client";
import { MODELS_CONSTANTS } from "@/shared/constants/models.constants";
import CommonService from "@/shared/services/common/common.service";
import FuseSvgIcon from "@fuse/core/FuseSvgIcon";
import { Box, Tab, Tabs, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import ListViewAction from "./ListViewAction";
import ListViewFields from "./ListViewFields";
import ListViewForm from "./ListViewForm";
import ListViewProvider from "./context/listViewContext";
const commonService = new CommonService();
const Listview = (props) => {
const [selectview, setselectview] = useState(0);
const [fieldData, setFieldData] = useState([]);
const [actionData, setActionData] = useState([]);
const listview = ["List View Form", "List View Field", "List View Action"];
const handleclicktab = (event, index) => {
setselectview(index);
};
const getFieldsData = async () => {
const response = await commonService.getDataByField(MODELS_CONSTANTS?.LIST_FIELDS, "list_view_id", props?.rowData._id);
if (response.status === 200) {
setFieldData(response.data.data);
}
};
const getActionData = async () => {
const response = await commonService.getDataByField(MODELS_CONSTANTS?.LIST_ACTIONS, "list_view_id", props?.rowData._id);
if (response.status === 200) {
setActionData(response.data.data);
}
};
useEffect(() => {
if (props?.rowData._id) {
getFieldsData();
getActionData();
}
}, []);
return (
List View Setup
props.onClose()}>
heroicons-outline:x-mark
{listview.map((item, index) => {
return ;
})}
{selectview === 0 && }
{selectview === 1 && }
{selectview === 2 && }
);
};
export default Listview;
< /code>
Каждый компонент вкладки имеет использование для заполнения деталей в режиме редактирования. < /p>
const ListViewForm = ({ formRowData }) => {
const { setListModule, listViewFormData, setListViewFormData } = useContext(ListViewContext);
const dispatch = useAppDispatch();
const [open, setOpen] = useState(false)
type FormType = {
list_name?: { name: string; value: string } | string;
display_type?: { display_type: string; value: string } | string;
list_type?: { list_type: string; value: string } | string;
list_description?: { description: string; value: string } | string;
api_registry?: { api_registry: string; value: string } | string;
module?: { module: string; value: string } | string;
reference_type?: { name: string; value: string } | string;
reference_id?: { reference_id: string; value: string } | string;
drawer_width?: { drawer_width: string; value: string } | string;
size?: { class: string; value: string } | string;
tile_type?: { tile_type: string; value: string } | string;
selected_tab?: { selected_tab: string; value: string } | string;
unique_fields?: any;
enable_delete?: boolean;
enable_inline_edit?: boolean;
common_title?: { common_title: string; value: string } | string;
};
const display_type = [
{ name: "--", value: "--" },
{ name: "Tile", value: "tile" },
{ name: "Grid", value: "grid" },
];
const list_type = [
{ name: "--", value: "--" },
{ name: "Search", value: "search" },
{ name: "Processing", value: "processing" },
{ name: "Report", value: "report" },
];
const drawer_width = [
{ name: "--", value: "--" },
{ name: "100%", value: "100%" },
{ name: "75%", value: "75%" },
{ name: "50%", value: "50%" },
{ name: "25%", value: "25%" },
];
const selected_tab = [{ name: "--", value: "--" }];
const unique_fields = [
{ name: "--", value: "--" },
{ name: "Order ID", value: "orderid" },
{ name: "InfoCard", value: "infocard" },
];
const { control, handleSubmit, watch, setValue, reset } = useForm({
mode: "onChange",
defaultValues: listViewFormData,
});
const formData = watch();
const formValues = useWatch({ control }); // Watch form values
useEffect(() => {
setListViewFormData(formValues); // Update state on value change
}, [formValues, setListViewFormData]);
const [modules, setModules] = useState([]);
const [initAction, setInitAction] = useState([]);
const [reference, setreference] = useState([]);
const [referenceid, setreferenceid] = useState([]);
const [classtype, setclasstype] = useState([]);
const [tiletype, settiletype] = useState([]);
useEffect(() => {
commonService.getAllData(MODELS_CONSTANTS.MODULES).then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.entity_name,
value: item?.entity_code,
_id: item?.collection_id,
}));
setModules(module_arr);
});
commonService.getAllData(MODELS_CONSTANTS.API_REGISTRIES).then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.api_name,
value: item?._id,
}));
setInitAction(module_arr);
});
commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "FORM_COMPONENTS").then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.vsd_code,
value: item?.vsd_code,
}));
setreference(module_arr);
});
commonService.getAllData(MODELS_CONSTANTS.FORM_SETUP).then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.form_name,
value: item?._id,
}));
setreferenceid(module_arr);
});
commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "CLASS_TYPE").then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.vsd_code,
value: item?.vsd_code,
}));
setclasstype(module_arr);
});
commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "TILE_TYPES").then((res) => {
const module_arr = res?.data?.data.map((item: any) => ({
name: item?.vsd_code,
value: item?._id,
}));
settiletype(module_arr);
});
}, []);
useEffect(() => {
reset({
list_name: formRowData?.list_view_name,
display_type: display_type.find((a) => a.value === formRowData.display_type),
list_type: list_type.find((a) => a.value === formRowData.list_type),
list_description: formRowData?.list_view_description,
api_registry: initAction.find((a) => a.value === formRowData?.api_id) || "",
module: modules.find((a) => a.value === formRowData?.module_id),
unique_fields: formRowData.unique_fields,
drawer_width: drawer_width.find((a) => a.name === formRowData.drawer_width),
reference_type: reference.find((a) => a.name === formRowData.reference_type),
reference_id: referenceid.find((a) => a.value === formRowData.reference_id),
tile_type: tiletype.find((a) => a.value === formRowData.tile_type) || "",
size: classtype.find((a) => a.value === formRowData.class_type),
enable_delete: formRowData.show_delete_yn,
enable_inline_edit: formRowData.inline_edit_yn,
common_title: formRowData?.common_title,
});
}, [tiletype]);
const return_id = (a, key) => {
if (typeof a[key] === "object") {
return a[key].value;
} else {
return a[key];
}
};
const array_id = (a, key) => {
if (a[key] === "array") {
return a[key].value;
} else {
return a[key];
}
};
const onSubmit = async (data: FormType) => {
const listformpayload = {
...formRowData,
list_view_name: data.list_name ? return_id(data, "list_name") : "",
display_type: data.display_type ? return_id(data, "display_type") : "",
list_type: data.list_type ? return_id(data, "list_type") : "",
list_view_description: data.list_description ? return_id(data, "list_description") : "",
api_id: data.api_registry ? return_id(data, "api_registry") : "",
module_id: data.module ? return_id(data, "module") : "",
reference_type: data.reference_type ? return_id(data, "reference_type") : "",
reference_id: data.reference_id ? return_id(data, "reference_id") : "",
drawer_width: data.drawer_width ? return_id(data, "drawer_width") : "",
class_type: data.size ? return_id(data, "size") : "",
tile_type: data.tile_type ? return_id(data, "tile_type") : "",
selected_tab: data.selected_tab ? return_id(data, "selected_tab") : "",
unique_fields: data.unique_fields ? array_id(data, "unique_fields") : "",
common_title: data.common_title,
show_delete_yn: data.enable_delete,
inline_edit_yn: data.enable_inline_edit,
};
const response = await commonService.saveRecord(MODELS_CONSTANTS.LIST_VIEW, listformpayload);
if (response.status === 200) {
dispatch(showMessage({ message: "Data Saved Successfully" }));
}
};
const setModelSchema = (item) => {
setListModule(item);
dispatch(closeDialog())
}
Вышеуказанные функции находятся в первом компоненте вкладки.
Подробнее здесь:
https://stackoverflow.com/questions/795 ... in-multipl
1744142798
Anonymous
Я создал компонент с тремя вкладками. Каждая вкладка имеет форму. Я ввожу детали в первой форме и перехожу во вторую форму. После этого я снова возвращаюсь к первой форме, и форма вернулась к начальному состоянию. Как этого избежать? < /P> [code]"use client"; import { MODELS_CONSTANTS } from "@/shared/constants/models.constants"; import CommonService from "@/shared/services/common/common.service"; import FuseSvgIcon from "@fuse/core/FuseSvgIcon"; import { Box, Tab, Tabs, Typography } from "@mui/material"; import { useEffect, useState } from "react"; import ListViewAction from "./ListViewAction"; import ListViewFields from "./ListViewFields"; import ListViewForm from "./ListViewForm"; import ListViewProvider from "./context/listViewContext"; const commonService = new CommonService(); const Listview = (props) => { const [selectview, setselectview] = useState(0); const [fieldData, setFieldData] = useState([]); const [actionData, setActionData] = useState([]); const listview = ["List View Form", "List View Field", "List View Action"]; const handleclicktab = (event, index) => { setselectview(index); }; const getFieldsData = async () => { const response = await commonService.getDataByField(MODELS_CONSTANTS?.LIST_FIELDS, "list_view_id", props?.rowData._id); if (response.status === 200) { setFieldData(response.data.data); } }; const getActionData = async () => { const response = await commonService.getDataByField(MODELS_CONSTANTS?.LIST_ACTIONS, "list_view_id", props?.rowData._id); if (response.status === 200) { setActionData(response.data.data); } }; useEffect(() => { if (props?.rowData._id) { getFieldsData(); getActionData(); } }, []); return ( List View Setup props.onClose()}> heroicons-outline:x-mark {listview.map((item, index) => { return ; })} {selectview === 0 && } {selectview === 1 && } {selectview === 2 && } ); }; export default Listview; < /code> Каждый компонент вкладки имеет использование для заполнения деталей в режиме редактирования. < /p> const ListViewForm = ({ formRowData }) => { const { setListModule, listViewFormData, setListViewFormData } = useContext(ListViewContext); const dispatch = useAppDispatch(); const [open, setOpen] = useState(false) type FormType = { list_name?: { name: string; value: string } | string; display_type?: { display_type: string; value: string } | string; list_type?: { list_type: string; value: string } | string; list_description?: { description: string; value: string } | string; api_registry?: { api_registry: string; value: string } | string; module?: { module: string; value: string } | string; reference_type?: { name: string; value: string } | string; reference_id?: { reference_id: string; value: string } | string; drawer_width?: { drawer_width: string; value: string } | string; size?: { class: string; value: string } | string; tile_type?: { tile_type: string; value: string } | string; selected_tab?: { selected_tab: string; value: string } | string; unique_fields?: any; enable_delete?: boolean; enable_inline_edit?: boolean; common_title?: { common_title: string; value: string } | string; }; const display_type = [ { name: "--", value: "--" }, { name: "Tile", value: "tile" }, { name: "Grid", value: "grid" }, ]; const list_type = [ { name: "--", value: "--" }, { name: "Search", value: "search" }, { name: "Processing", value: "processing" }, { name: "Report", value: "report" }, ]; const drawer_width = [ { name: "--", value: "--" }, { name: "100%", value: "100%" }, { name: "75%", value: "75%" }, { name: "50%", value: "50%" }, { name: "25%", value: "25%" }, ]; const selected_tab = [{ name: "--", value: "--" }]; const unique_fields = [ { name: "--", value: "--" }, { name: "Order ID", value: "orderid" }, { name: "InfoCard", value: "infocard" }, ]; const { control, handleSubmit, watch, setValue, reset } = useForm({ mode: "onChange", defaultValues: listViewFormData, }); const formData = watch(); const formValues = useWatch({ control }); // Watch form values useEffect(() => { setListViewFormData(formValues); // Update state on value change }, [formValues, setListViewFormData]); const [modules, setModules] = useState([]); const [initAction, setInitAction] = useState([]); const [reference, setreference] = useState([]); const [referenceid, setreferenceid] = useState([]); const [classtype, setclasstype] = useState([]); const [tiletype, settiletype] = useState([]); useEffect(() => { commonService.getAllData(MODELS_CONSTANTS.MODULES).then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.entity_name, value: item?.entity_code, _id: item?.collection_id, })); setModules(module_arr); }); commonService.getAllData(MODELS_CONSTANTS.API_REGISTRIES).then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.api_name, value: item?._id, })); setInitAction(module_arr); }); commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "FORM_COMPONENTS").then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.vsd_code, value: item?.vsd_code, })); setreference(module_arr); }); commonService.getAllData(MODELS_CONSTANTS.FORM_SETUP).then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.form_name, value: item?._id, })); setreferenceid(module_arr); }); commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "CLASS_TYPE").then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.vsd_code, value: item?.vsd_code, })); setclasstype(module_arr); }); commonService.getDataByField(MODELS_CONSTANTS.VALUE_SET_DETAILS, "vs_code", "TILE_TYPES").then((res) => { const module_arr = res?.data?.data.map((item: any) => ({ name: item?.vsd_code, value: item?._id, })); settiletype(module_arr); }); }, []); useEffect(() => { reset({ list_name: formRowData?.list_view_name, display_type: display_type.find((a) => a.value === formRowData.display_type), list_type: list_type.find((a) => a.value === formRowData.list_type), list_description: formRowData?.list_view_description, api_registry: initAction.find((a) => a.value === formRowData?.api_id) || "", module: modules.find((a) => a.value === formRowData?.module_id), unique_fields: formRowData.unique_fields, drawer_width: drawer_width.find((a) => a.name === formRowData.drawer_width), reference_type: reference.find((a) => a.name === formRowData.reference_type), reference_id: referenceid.find((a) => a.value === formRowData.reference_id), tile_type: tiletype.find((a) => a.value === formRowData.tile_type) || "", size: classtype.find((a) => a.value === formRowData.class_type), enable_delete: formRowData.show_delete_yn, enable_inline_edit: formRowData.inline_edit_yn, common_title: formRowData?.common_title, }); }, [tiletype]); const return_id = (a, key) => { if (typeof a[key] === "object") { return a[key].value; } else { return a[key]; } }; const array_id = (a, key) => { if (a[key] === "array") { return a[key].value; } else { return a[key]; } }; const onSubmit = async (data: FormType) => { const listformpayload = { ...formRowData, list_view_name: data.list_name ? return_id(data, "list_name") : "", display_type: data.display_type ? return_id(data, "display_type") : "", list_type: data.list_type ? return_id(data, "list_type") : "", list_view_description: data.list_description ? return_id(data, "list_description") : "", api_id: data.api_registry ? return_id(data, "api_registry") : "", module_id: data.module ? return_id(data, "module") : "", reference_type: data.reference_type ? return_id(data, "reference_type") : "", reference_id: data.reference_id ? return_id(data, "reference_id") : "", drawer_width: data.drawer_width ? return_id(data, "drawer_width") : "", class_type: data.size ? return_id(data, "size") : "", tile_type: data.tile_type ? return_id(data, "tile_type") : "", selected_tab: data.selected_tab ? return_id(data, "selected_tab") : "", unique_fields: data.unique_fields ? array_id(data, "unique_fields") : "", common_title: data.common_title, show_delete_yn: data.enable_delete, inline_edit_yn: data.enable_inline_edit, }; const response = await commonService.saveRecord(MODELS_CONSTANTS.LIST_VIEW, listformpayload); if (response.status === 200) { dispatch(showMessage({ message: "Data Saved Successfully" })); } }; const setModelSchema = (item) => { setListModule(item); dispatch(closeDialog()) } [/code] Вышеуказанные функции находятся в первом компоненте вкладки. Подробнее здесь: [url]https://stackoverflow.com/questions/79562949/how-to-avoid-unnecessary-re-renders-in-react-while-working-with-forms-in-multipl[/url]