英文:
How to refactor my code, so the h2 header renders only when needed?
问题
以下是您要的代码部分的中文翻译:
import { DocumentData, onSnapshot, QuerySnapshot } from "firebase/firestore";
import { useEffect, useState } from "react";
import { hotelsCollection } from "../lib/controller";
import { NewHotelType } from "../types/hotel";
import Information from "./Information";
function Hotel() {
const [hotels, setHotels] = useState<NewHotelType[]>([]);
const [search, setSearch] = useState("");
const [sortState, setSortState] = useState("");
const [isLoading, setIsLoading] = useState(false);
useEffect(
() =>
onSnapshot(hotelsCollection, (snapshot: QuerySnapshot<DocumentData>) => {
setHotels(
snapshot.docs.map(doc => {
return {
id: doc.id,
...doc.data(),
};
})
);
}),
[]
);
if (isLoading) return <div>加载中..</div>;
return (
<div className="card">
<select
className="select"
defaultValue=""
onChange={(e) => setSortState(e.target.value)}
>
<option value="disabled">筛选</option>
<option value="name">名称</option>
<option value="price">价格</option>
</select>
<div className="search">
<input
className="inputsearch"
value={search}
type="text"
placeholder="搜索酒店"
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{hotels && hotels.length ? (
<div>
{hotels
?.filter((item: NewHotelType) => {
if (search === "" && !search.length) {
return item;
}
return item?.title === search;
})
.sort((a, b) => {
if (sortState === "name") {
if (a.title && b.title) return a.title.localeCompare(b.title);
}
if (sortState === "price") {
return Number(a.perNight) - Number(b.perNight);
}
return 0;
})
?.map((hotel: NewHotelType) => (
<Information key={hotel.id} hotel={hotel} />
))}
</div>
) : !isLoading ? (
<h2 className="no-hotels">暂无酒店,请添加一个</h2>
) : <div>加载中..</div>}
</div>
);
}
export default Hotel;
希望这对您有帮助。如果您需要进一步的翻译或有其他问题,请随时告诉我。
英文:
I have simple react component where I render a list of hotels. I fetch data from firebase. I added a statement which I want to render ONLY when there aren't any hotels on list. Currently this h2 tag renders every time when I refresh the browser, or click on the go back button. Could you please kindly advise how can I make it to render only when needed?
import { DocumentData, onSnapshot, QuerySnapshot } from "firebase/firestore";
import { useEffect, useState } from "react";
import { hotelsCollection } from "../lib/controller";
import { NewHotelType } from "../types/hotel";
import Information from "./Information";
function Hotel() {
const [hotels, setHotels] = useState<NewHotelType[]>([]);
const [search, setSearch] = useState("")
const [sortState, setSortState] = useState("");
const [isLoading, setIsLoading] = useState(false);
useEffect(
() =>
onSnapshot(hotelsCollection, (snapshot: QuerySnapshot<DocumentData>) => {
setHotels(
snapshot.docs.map(doc => {
return {
id: doc.id,
...doc.data(),
};
})
);
}),
[]
);
if(isLoading) return <div>Loading..</div>
return (
<div className="card">
<select
className="select"
defaultValue={""}
onChange={(e) => setSortState(e.target.value)}
>
<option value="disabled">Filter By</option>
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<div className="search">
<input
className="inputsearch"
value={search}
type="text"
placeholder="Search for the hotel"
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{hotels && hotels.length ? (
<div>
{hotels
?.filter((item: NewHotelType) => {
if (search === "" && !search.length) {
return item;
}
return item?.title === search;
})
.sort((a, b) => {
if (sortState === "name") {
if (a.title && b.title) return a.title.localeCompare(b.title);
}
if (sortState === "price") {
return Number(a.perNight) - Number(b.perNight);
}
return 0;
})
?.map((hotel: NewHotelType) => (
<Information key={hotel.id} hotel={hotel} />
))}
</div>
) : !isLoading ? (
<h2 className="no-hotels">There are no hotels. Please add one</h2>
) : <div>Loading..</div>}
</div>
);
}
export default Hotel;
答案1
得分: 1
你所做的是正确的。你需要管理加载状态。当你的组件首次渲染时,hotels状态是一个空数组,所以直到它被数据填充之前,你需要显示一个加载器,这样你就确保标题只在数组为空且数据加载完成后才渲染。
一种方法是设置一个初始为true的加载状态。一旦快照成功并将数据推送到状态中,你将把加载状态设置为false。换句话说,在setHotels(...)之后,你要把isLoading设置为false。
现在在你的JSX中,你可以为加载状态添加一个短路条件,例如:if(loading) return <Loader />
更新:
function Hotel() {
const [hotels, setHotels] = useState<NewHotelType[]>([]);
const [search, setSearch] = useState("");
const [sortState, setSortState] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(
() =>
onSnapshot(hotelsCollection, (snapshot: QuerySnapshot<DocumentData>) => {
setHotels(
snapshot.docs.map((doc) => {
return {
id: doc.id,
...doc.data(),
};
})
);
setIsLoading(false)
}),
[]
);
if (isLoading) return <div>Loading..</div>;
return (
<div className="card">
<select
className="select"
defaultValue=""
onChange={(e) => setSortState(e.target.value)}
>
<option value="disabled">Filter By</option>
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<div className="search">
<input
className="inputsearch"
value={search}
type="text"
placeholder="Search for the hotel"
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{hotels && hotels.length ? (
<div>
{hotels
?.filter((item: NewHotelType) => {
if (search === "" && !search.length) {
return item;
}
return item?.title === search;
})
.sort((a, b) => {
if (sortState === "name") {
if (a.title && b.title) return a.title.localeCompare(b.title);
}
if (sortState === "price") {
return Number(a.perNight) - Number(b.perNight);
}
return 0;
})
?.map((hotel: NewHotelType) => (
<Information key={hotel.id} hotel={hotel} />
))}
</div>
) : (
<h2 className="no-hotels">There are no hotels. Please add one</h2>
)}
</div>
);
}
英文:
What you've done is correct. What you need, is to manage the loading state as well. When your component first renders your hotels state is an empty array, so till it gets filled by the data, you need to show a Loader, that way you make sure that the title is only rendering when the array is empty and the data has finished loading.
One way of doing it, is having a loading state that you set initially to true. and once your snapshot is successful and you pushed the data to the state, you will set the loading to false. In other words, after setHotels(...) you want to setLoading to false.
Now in your JSX you want to add a short circuit for the loading state,eg: if(loading) return <Loader />
Update:
function Hotel() {
const [hotels, setHotels] = useState<NewHotelType[]>([]);
const [search, setSearch] = useState("");
const [sortState, setSortState] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(
() =>
onSnapshot(hotelsCollection, (snapshot: QuerySnapshot<DocumentData>) => {
setHotels(
snapshot.docs.map((doc) => {
return {
id: doc.id,
...doc.data(),
};
})
);
setIsLoading(false)
}),
[]
);
if (isLoading) return <div>Loading..</div>;
return (
<div className="card">
<select
className="select"
defaultValue={""}
onChange={(e) => setSortState(e.target.value)}
>
<option value="disabled">Filter By</option>
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<div className="search">
<input
className="inputsearch"
value={search}
type="text"
placeholder="Search for the hotel"
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{hotels && hotels.length ? (
<div>
{hotels
?.filter((item: NewHotelType) => {
if (search === "" && !search.length) {
return item;
}
return item?.title === search;
})
.sort((a, b) => {
if (sortState === "name") {
if (a.title && b.title) return a.title.localeCompare(b.title);
}
if (sortState === "price") {
return Number(a.perNight) - Number(b.perNight);
}
return 0;
})
?.map((hotel: NewHotelType) => (
<Information key={hotel.id} hotel={hotel} />
))}
</div>
) : (
<h2 className="no-hotels">There are no hotels. Please add one</h2>
)}
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论