OrganizationsView.jsx почему отображаются на странички данные как из ProductView.jsx?…
- User
OrganizationsView.jsx почему отображаются на странички данные как из ProductView.jsx?
import React, { useEffect, useState } from "react"; import OrganizationService from "../../api/services/organization-service"; import { Table, Button, Space, Modal, Form, Input } from "antd"; import { EditOutlined, DeleteOutlined } from "@ant-design/icons"; export const OrganizationsView = ({ ...props }) => { const columns = [ { title: 'ID', dataIndex: 'id', key: 'id', }, { title: 'Название', dataIndex: 'title', key: 'title', }, { title: 'ИНН', dataIndex: 'inn', key: 'inn', }, { title: 'Действия', key: 'actions', render: (text, record) => { return ( <Space size="middle"> <div onClick={() => updateRecordHandler(record)}> <EditOutlined /> </div> <div onClick={() => deleteRecordHandler(record.id)}> <DeleteOutlined /> </div> </Space> ) } } ]; const handleOk = async () => { try { if (currentRecord?.id) { await OrganizationService.updateRecord(currentRecord); } else { await OrganizationService.createRecord(currentRecord); } const updatedList = await OrganizationService.getAllRecords(); setList(updatedList); setVisible(false); setCurrentRecord(null); } catch (error) { console.error('Ошибка при сохранении данных:', error); } }; const handleCancel = () => { setVisible(false); }; const createRecordHandler = () => { setCurrentRecord(null); setVisible(true); } const updateRecordHandler = (record) => { setCurrentRecord(record); setVisible(true); } const deleteRecordHandler = async (recordId) => { await OrganizationService.removeRecord(recordId); setList(list.filter(it => it.id !== recordId)); } const [list, setList] = useState([]); const [currentRecord, setCurrentRecord] = useState(null); const [visible, setVisible] = useState(false); useEffect(() => { async function fetchData() { const list = await OrganizationService.getAllRecords(); setList(list); return () => setList([]); } fetchData(); }, []) return ( <div style={{ padding: 16 }}> <Table dataSource={list} columns={columns} rowKey="id" /> <Button onClick={createRecordHandler}> Создать </Button> <Modal title={currentRecord ? "Обновить организацию" : "Создать организацию"} visible={visible} onOk={handleOk} onCancel={handleCancel} > <Form layout="vertical"> <Form.Item label="Название" required> <Input value={currentRecord ? currentRecord.title : ''} onChange={(e) => setCurrentRecord({ ...currentRecord, title: e.target.value })} /> </Form.Item> <Form.Item label="ИНН" required> <Input value={currentRecord ? currentRecord.inn : ''} onChange={(e) => setCurrentRecord({ ...currentRecord, inn: e.target.value })} /> </Form.Item> </Form> </Modal> </div> ); } - Assistant
There are several possible reasons why your
OrganizationsView.jsxmight be showing data that looks like it comes fromProductView.jsx. Here are some areas to check:-
Data Initialization:
- Check
OrganizationService.getAllRecords()to ensure that it fetches organization data, not product data. Perhaps the service is incorrectly fetching data from a product-related endpoint.
- Check
-
- User
на русском
- Assistant
Конечно, давайте разберёмся с этой проблемой на русском:
Если в вашем компоненте
OrganizationsView.jsxотображаются данные, похожие на данные изProductView.jsx, вот несколько возможных причин и путей их проверки: - User
вот organization-service.js:
import { instanceAxios } from "../axios-config"; export default class OrganizationService { static apiUrl = '/api/organizations'; /** * Получить все записи * @returns {Promise<any>} */ static async getAllRecords() { const res = await instanceAxios.get(this.apiUrl); return res.data; } /** * Создать запись * @param {Object} body - Данные для создания новой записи * @returns {Promise<any>} */ static async createRecord(body) { const res = await instanceAxios.post(this.apiUrl, body); return res.data; } /** * Обновить запись * @param {Object} body - Данные для обновления записи * @returns {Promise<any>} */ static async updateRecord(body) { const res = await instanceAxios.put(`${this.apiUrl}/${body.id}`, body); return res.data; } /** * Удалить запись * @param {number|string} recordId - Идентификатор записи для удаления * @returns {Promise<any>} */ static async removeRecord(recordId) { const res = await instanceAxios.delete(`${this.apiUrl}/${recordId}`); return res.data; } } - Assistant
Ваш
OrganizationService.jsвыглядит корректно с точки зрения методов для работы с API. Давайте рассмотрим еще раз возможные причины, по которым данные могут отображаться неправильно. Проделайте следующие шаги:-
Проверьте URL API:
- Убедитесь, что в действительно соответствует URL, который возвращает данные об организациях. Проверьте, нет ли ошибок в конфигурации маршрутов на серверной стороне.
-
- User
Не из той таблицы данные вытягивает, как исправить?
- Assistant
Если ваш компонент
OrganizationsView.jsxотображает данные из неправильной таблицы (например, данные из таблицы продуктов вместо таблицы организаций), скорее всего, проблема связана с тем, что неправильно настроен источник данных в вашем API запросе. - User
У меня в бекенде есть controllers, models, routers, services. Куда идти дальше?
- Assistant
- User
organization-controller.js
const OrganizationService = require('../services/organization-service'); class OrganizationController { async getAllOrganizations(req, res) { try { const list = await OrganizationService.getAllRecords(); return res .status(200) .json(list); } catch (e) { return res .status(500) .json(e); } } async createOrganization(req, res) { try { const organization = await OrganizationService.createRecord(req.body); return res .status(201) .json(organization); } catch (e) { return res .status(500) .json(e); } } async updateOrganization(req, res) { try { const organization = await OrganizationService.updateRecord(req.body); return res .status(200) .json(organization); } catch (e) { return res .status(500) .json(e); } } async removeOrganization(req, res) { try { const organizationId = req.params.id; const organization = await OrganizationService.removeRecord(organizationId); return res .status(200) .json(organization); } catch (e) { return res .status(500) .json(e); } } } module.exports = new OrganizationController(); - Assistant
- User
routers.js:
const Router = require('express').Router; const ProductController = require('../controllers/product-controller'); const IndividualController = require('../controllers/individual-controller'); const OrganizationController = require('../controllers/organization-controller'); const ProxyHeaderController = require('../controllers/proxy-header-controller'); const ProxyBodyController = require('../controllers/proxy-body-controller'); const router = new Router(); // Product routes router.get('/products', ProductController.getAllRecords); router.post('/products', ProductController.createRecord); router.put('/products', ProductController.updateRecord); router.delete('/products/:id', ProductController.removeRecord); // Individual routes router.get('/individuals', IndividualController.getAllIndividuals); router.post('/individuals', IndividualController.createIndividual); router.put('/individuals/:id', IndividualController.updateIndividual); router.delete('/individuals/:id', IndividualController.removeIndividual); // Organization routes router.get('/organizations', OrganizationController.getAllOrganizations); router.post('/organizations', OrganizationController.createOrganization); router.put('/organizations/:id', OrganizationController.updateOrganization); router.delete('/organizations/:id', OrganizationController.removeOrganization); // Proxy Header routes router.get('/proxyheaders', ProxyHeaderController.getAllProxyHeaders); router.post('/proxyheaders', ProxyHeaderController.createProxyHeader); router.put('/proxyheaders/:id', ProxyHeaderController.updateProxyHeader); router.delete('/proxyheaders/:id', ProxyHeaderController.removeProxyHeader); router.get('/proxyheaders/:id', ProxyHeaderController.getOneProxyHeader); // Proxy Body routes router.get('/proxybodies', ProxyBodyController.getAllProxyBodies); router.post('/proxybodies', ProxyBodyController.createProxyBody); router.put('/proxybodies/:id', ProxyBodyController.updateProxyBody); router.delete('/proxybodies/:id', ProxyBodyController.removeProxyBody); module.exports = router; - Assistant
- User
organization-service.js:
const OrganizationModel = require('../models/product-model'); class OrganizationService { /** получить все записи из таблицы "products" */ async getAllRecords() { const list = await OrganizationModel.findAll(); return list; } /** создать запись в таблице "products" */ async createRecord(payload) { const data = await OrganizationModel.create(payload); return data; } /** обновить запись в таблице "products" */ async updateRecord(payload) { let record = await OrganizationModel.findOne({ where: { id: payload.id } }); record.title = payload?.title || record.title; return await record.save(); } /** удалить запись из таблицы "products" */ async removeRecord(recordId) { const record = await OrganizationModel.destroy({ where: { id: recordId } }); return record; } } module.exports = new OrganizationService(); - Assistant
Похоже, что проблема заключается в том, что в вашем файле
organization-service.jsиспользуетсяOrganizationModel, который на самом деле является моделью для продуктов.Как исправить:
-
Использование правильной модели:
- Измените импорт модели с
product-modelнаorganization-modelвorganization-service.js. Это позволит вашему сервису взаимодействовать с правильной таблицей в базе данных.
const OrganizationModel = require('../models/organization-model'); - Измените импорт модели с
-
Проверка методов:
-