我有一个简单的页面,其中有一个表格和一个按钮 该按钮打开一个带有表单的模式,通过 api url 将数据插入到数据库
此页面上有一个表格,显示数据库内部的内容
但仍在学习,当我使用模态时,查询有效,但表不更新 如何使表格在模态过程完成时更新?
这是表格组件
//"use client";
//import { useState } from "react";
import Link from "next/link";
/* ------------------------------ Buscar dados ------------------------------ */
async function getSurveys() {
const APIURL = process.env.API_URL;
const res = await fetch(`${APIURL}/api/surveys`, {
method: "GET",
});
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}
export async function TableSurveys() {
const surveysData: any[] = await getSurveys();
const surveys = Array.from(surveysData);
return (
<table className="table">
<thead>
<tr>
<th scope="col">Nome</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{surveys.map((survey) => (
<tr key={survey.id}>
<td className="align-middle">{survey.name}</td>
<td className="text-end">
<Link
href={`/avaliacao/${survey.id}`}
className="btn btn-sm btn-outline-primary me-2"
>
Entrar
</Link>
<button
type="button"
className="btn btn-sm btn-light part_del"
data-bs-toggle="modal"
data-bs-target="#modal_excluir"
data-aval-id={survey.id}
>
<span className="btn-label">
<i className="fa fa-trash"></i>
</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
这是按钮模态组件
"use client";
import { useState } from "react";
import { v4 } from "uuid";
import { FormEvent } from "react";
/* ------------------------------- components ------------------------------- */
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";
import Form from "react-bootstrap/Form";
/* -------------------------- renderizar componente ------------------------- */
export function ModalNewSurvey() {
const [modalNewAval, setModalNewAval] = useState(false);
const [nomeAvaliacao, setNomeAvaliacao] = useState("");
const handleShow = () => setModalNewAval(true);
const handleClose = () => {
setNomeAvaliacao(""); // Clear the input field
setModalNewAval(false);
};
// adicionar survey
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); // nao submita o form
const formData = new FormData(event.currentTarget); // pega os dados
handleClose(); // fecha o modal
// Gera um ID usando a função uuidv4()
const id = v4();
// Adiciona o ID ao formulário
formData.append("id", id);
// Converte os dados em JSON
const data = JSON.stringify({
id: formData.get("id"),
name: formData.get("name"),
});
//console.log(data);
const APIURL = process.env.API_URL; // pega url
const response = await fetch(`/api/surveys`, {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
},
});
//console.log(formData);
// Handle response if necessary
//const data = await response.json();
// ...
}
return (
<>
<Button onClick={handleShow} className="me-2">
<span className="btn-label">
<i className="fa fa-plus me-2"></i>
</span>
Criar Avaliação
</Button>
<Modal
show={modalNewAval}
onHide={handleClose}
aria-labelledby="example-modal-sizes-title-sm"
>
<Modal.Header closeButton>
<Modal.Title id="example-modal-sizes-title-sm">
Criar Avaliação
</Modal.Title>
</Modal.Header>
<Form onSubmit={onSubmit}>
<Modal.Body>
<Form.Group className="mb-3" controlId="NomeAvaliacao">
<Form.Label>Nome da Avaliação</Form.Label>
<Form.Control
type="text"
placeholder="ex: Setor Administrativo 1"
value={nomeAvaliacao}
name="name"
onChange={(e) => setNomeAvaliacao(e.target.value)}
/>
</Form.Group>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Cancelar
</Button>
<Button type="submit">Criar Avaliação</Button>
</Modal.Footer>
</Form>
</Modal>
</>
);
}
这是页面
/* -------------------------------- metadata -------------------------------- */
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Avaliações",
};
/* ------------------------------- components ------------------------------- */
import { ModalNewSurvey } from "@/app/comps/modal_new_survey";
import { TableSurveys } from "@/app/comps/table_surveys";
/* ---------------------------- renderizar pagina --------------------------- */
export default async function SurveysPage() {
return (
<>
<div className="container mt-4">
<div className="container mt-3 mt-sm-5 mb-3">
<div className="row ">
<div className="col-md">
<h2>Avaliações</h2>
<p>Crie avaliações e seus grupos de participantes.</p>
</div>
<div className="col-md-auto text-md-end text-end d-grid gap-2 d-md-block">
<ModalNewSurvey />
</div>
</div>
</div>
<TableSurveys />
</div>
</>
);
}
一些简单的解决方案或者聪明的解决方案 我在 next.js 上有最新的服务器组件规则:/
要在通过模式添加数据后更新表格,您可以在 Next.js 应用程序中执行以下步骤:
1:传递函数来更新数据:创建状态管理机制(例如 React 状态)来管理填充表的数据。您还应该将一个函数传递给 ModalNewSurvey 组件,以允许其更新此数据。
2:更新模态组件中的数据:通过模态成功添加数据后,调用您在步骤 1 中传递的更新函数来刷新父组件(页面)中的数据。
以下是如何实现此目的的简化示例:
// In your SurveysPage component
import { useState, useEffect } from "react";
export default function SurveysPage() {
const [surveys, setSurveys] = useState([]);
// Function to update the surveys data
const updateSurveys = (newSurvey) => {
setSurveys([...surveys, newSurvey]);
};
useEffect(() => {
// Load initial data when the page loads
async function fetchSurveys() {
const surveysData = await getSurveys();
setSurveys(surveysData);
}
fetchSurveys();
}, []);
return (
<>
{/* ... other code ... */}
<ModalNewSurvey updateSurveys={updateSurveys} />
<TableSurveys surveys={surveys} />
</>
);
}
在 ModalNewSurvey 组件中:
export function ModalNewSurvey({ updateSurveys }) {
// ... other code ...
async function onSubmit(event) {
// ... other code ...
// After successfully adding data, call the update function
// to refresh the data in the parent component.
updateSurveys({ id, name });
}
return (
// ... modal code ...
);
}
通过此设置,当您在模态中提交表单并成功添加数据时,它将调用父组件中的
updateSurveys
函数,从而更新 surveys
状态。因此,TableSurveys
组件将使用更新后的数据重新呈现,从而有效地刷新页面上的表格。