我遇到的问题是,当我通过模态组件向数据库添加数据时,新数据不会立即出现在表中。它只有在我刷新页面后才会显示。我尝试实现刷新键逻辑来重新获取组件,但它不起作用。我希望新数据在通过模式添加后立即反映在表中,而不需要手动刷新。数据表组件是我调用模态和表格的地方。
import React, { useState, useEffect } from "react";
import ReviewFeature from "./ReviewFeature";
import ArtistModal from "./ArtistModal";
import Dropdown from "./Dropdown";
import Layout from "../../Components/Layout";
import { fetchReviewArtist, searchArtist } from "../../Services/Api";
const ReviewDataTable = () => {
const [modalIsOpen, setModalIsOpen] = useState(false);
const [dropdownVisible, setDropdownVisible] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [filteredItems, setFilteredItems] = useState([]);
const [artists, setArtists] = useState([]);
const [refreshKey, setRefreshKey] = useState(0);
useEffect(() => {
const fetchArtists = async () => {
try {
const response = await fetchReviewArtist();
console.log("Fetched artists:", response);
setArtists(response);
console.log("set artist", setArtists);
} catch (error) {
console.error("Error fetching artists:", error);
}
};
fetchArtists();
},[refreshKey] );
const fetchSpotifyArtists = async (query) => {
try {
const artists = await searchArtist(query);
console.log("artists:", artists);
setFilteredItems(artists);
console.log("Filtered items:", artists);
} catch (error) {
console.error("Error fetching Spotify artistssssss:", error);
setFilteredItems([]);
}
};
const [formData, setFormData] = useState({
name: "",
photo: "",
location: "",
bio: "",
genre: " ",
platforms: "",
age: "",
spotifyId: "",
});
useEffect(() => {
if (searchTerm) {
fetchSpotifyArtists(searchTerm);
} else {
setFilteredItems([]);
}
}, [searchTerm]);
const handleSelectArtist = async (artist) => {
console.log("Artist before destrufture:", artist);
const { name, photo, spotifyId } = artist;
const artistImage = artist.image || "path/to/default/image.jpg";
const artistGenres = "Unknown genre";
const newFormData = {
name,
photo: artistImage,
location: "",
bio: "",
genre: artistGenres,
platforms: "",
age: "",
spotifyId: spotifyId,
};
setFormData(newFormData);
console.log("Setting form data:", { name, photo: artistImage });
setDropdownVisible(false);
setModalIsOpen(true);
};
const openModal = () => {
setModalIsOpen(true);
};
const closeModal = () => {
setModalIsOpen(false);
};
const addArtist = (newArtist) => {
setArtists((prevArtists) => [...prevArtists, newArtist]);
console.log("refreshkey:",refreshKey);
closeModal();
};
const deleteArtist = (name) => {
setArtists((prevArtists) =>
prevArtists.filter((artist) => artist.name !== name)
);
};
return (
<Layout>
<div className="flex flex-col w-full h-[500] overflow-y-auto bg-customBlue mt-12">
<div className="p-4 bg-customBlue text-white overflow-hidden">
<div className="flex flex-row gap-12">
<h1
className="text-2xl font-semibold text-white ml-10 mb-4"
style={{ fontFamily: "Poppins" }}
>
Artists
</h1>
<div className="flex items-center space-x-4">
<div className="relative flex flex-row">
<input
type="text"
placeholder="Search for..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={() => setDropdownVisible(true)}
className="p-2 pl-10 rounded-md border bg-customColor w-[260.75px] h-[46px] text-white mb-4"
style={{
borderRadius: "4px",
border: "0.6px solid #343B4F",
}}
/>
{/* <img
src="./assests/Search.png"
alt="Search Icon"
className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5"
/> */}
</div>
</div>
<button
onClick={openModal}
className="w-[105px] h-[44px] bg-customBlue text-white mt-2 border-white rounded p-2 flex justify-center items-center"
style={{
border: "1px solid #ffffff",
position: "relative",
left: "630px",
}}
>
<span className="font-poppins" style={{ whiteSpace: "nowrap" }}>
+ Add Artist
</span>
</button>
</div>
{dropdownVisible && searchTerm && (
<Dropdown items={filteredItems} onSelect={handleSelectArtist} />
)}
<ReviewFeature data={artists} onDelete={deleteArtist} />
<ArtistModal
isOpen={modalIsOpen}
onRequestClose={closeModal}
onSave={(newArtist) => {
addArtist(newArtist);
setRefreshKey((oldKey) => oldKey + 1);
}}
preFilledData={{
name: formData.name,
photo: formData.photo,
spotifyId: formData.spotifyId,
}}
/>
</div>
</div>
</Layout>
);
};
export default ReviewDataTable;
您正在使用 setArtists 更新状态并增加刷新键,但刷新键没有正确触发重新获取。
试试这个:
import React, { useState, useEffect } from "react";
import ReviewFeature from "./ReviewFeature";
import ArtistModal from "./ArtistModal";
import Dropdown from "./Dropdown";
import Layout from "../../Components/Layout";
import { fetchReviewArtist, searchArtist } from "../../Services/Api";
const ReviewDataTable = () => {
const [modalIsOpen, setModalIsOpen] = useState(false);
const [dropdownVisible, setDropdownVisible] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [filteredItems, setFilteredItems] = useState([]);
const [artists, setArtists] = useState([]);
useEffect(() => {
const fetchArtists = async () => {
try {
const response = await fetchReviewArtist();
console.log("Fetched artists:", response);
setArtists(response);
} catch (error) {
console.error("Error fetching artists:", error);
}
};
fetchArtists();
}, []); // Only run on mount
const fetchSpotifyArtists = async (query) => {
try {
const artists = await searchArtist(query);
console.log("artists:", artists);
setFilteredItems(artists);
} catch (error) {
console.error("Error fetching Spotify artists:", error);
setFilteredItems([]);
}
};
const [formData, setFormData] = useState({
name: "",
photo: "",
location: "",
bio: "",
genre: " ",
platforms: "",
age: "",
spotifyId: "",
});
useEffect(() => {
if (searchTerm) {
fetchSpotifyArtists(searchTerm);
} else {
setFilteredItems([]);
}
}, [searchTerm]);
const handleSelectArtist = async (artist) => {
const { name, photo, spotifyId } = artist;
const artistImage = artist.image || "path/to/default/image.jpg";
const artistGenres = "Unknown genre";
const newFormData = {
name,
photo: artistImage,
location: "",
bio: "",
genre: artistGenres,
platforms: "",
age: "",
spotifyId: spotifyId,
};
setFormData(newFormData);
setDropdownVisible(false);
setModalIsOpen(true);
};
const openModal = () => {
setModalIsOpen(true);
};
const closeModal = () => {
setModalIsOpen(false);
};
const addArtist = (newArtist) => {
setArtists((prevArtists) => [...prevArtists, newArtist]);
closeModal();
};
const deleteArtist = (name) => {
setArtists((prevArtists) =>
prevArtists.filter((artist) => artist.name !== name)
);
};
return (
<Layout>
<div className="flex flex-col w-full h-[500] overflow-y-auto bg-customBlue mt-12">
<div className="p-4 bg-customBlue text-white overflow-hidden">
<div className="flex flex-row gap-12">
<h1
className="text-2xl font-semibold text-white ml-10 mb-4"
style={{ fontFamily: "Poppins" }}
>
Artists
</h1>
<div className="flex items-center space-x-4">
<div className="relative flex flex-row">
<input
type="text"
placeholder="Search for..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={() => setDropdownVisible(true)}
className="p-2 pl-10 rounded-md border bg-customColor w-[260.75px] h-[46px] text-white mb-4"
style={{
borderRadius: "4px",
border: "0.6px solid #343B4F",
}}
/>
</div>
</div>
<button
onClick={openModal}
className="w-[105px] h-[44px] bg-customBlue text-white mt-2 border-white rounded p-2 flex justify-center items-center"
style={{
border: "1px solid #ffffff",
position: "relative",
left: "630px",
}}
>
<span className="font-poppins" style={{ whiteSpace: "nowrap" }}>
+ Add Artist
</span>
</button>
</div>
{dropdownVisible && searchTerm && (
<Dropdown items={filteredItems} onSelect={handleSelectArtist} />
)}
<ReviewFeature data={artists} onDelete={deleteArtist} />
<ArtistModal
isOpen={modalIsOpen}
onRequestClose={closeModal}
onSave={(newArtist) => {
addArtist(newArtist);
}}
preFilledData={{
name: formData.name,
photo: formData.photo,
spotifyId: formData.spotifyId,
}}
/>
</div>
</div>
</Layout>
);
};
export default ReviewDataTable;