我尝试呈现两个日期之间的音乐会列表。问题是用户需要首先在页面上选择所需的日期,然后整个过滤功能才能运行。组件中只有一个useEffect
,我不能在那里过滤,因为start date
和end date
是必需的。所以我把我的过滤功能移到useEffect
之外,现在我得到无限循环。如何以最好和专业的方式解决这个问题?
import React from "react";
import axios from "axios";
import { useState, useEffect } from "react";
const Explore = () => {
//Raw JSON Date example: "2023-02-08T23:15:30.000Z"
let currentDate = new Date().toJSON().slice(0, 10);
const [concerts, setConcerts] = useState([]);
const [startDate, setStartDate] = useState(currentDate);
const [endDate, setEndDate] = useState(currentDate);
const [limit, setLimit] = useState(25);
useEffect(() => {
const loadConcerts = async () => {
const request = await axios.get("data/concerts");
setConcerts(request.data);
};
loadConcerts();
}, []);
const filtered = concerts.filter((concert) => {
return concert.datum >= startDate && concert.datum <= endDate;
});
setConcerts(filtered);
if (!filtered.length) {
return <h1>Loading</h1>;
}
return (
<div>
<label for="start">Start date:</label>
<label for="end">End date:</label>
<input
type="date"
id="start"
value={startDate}
min="2023-01-01"
max="2030-12-31"
onChange={(event) => setStartDate(event.target.value)}
/>
<input
type="date"
id="end"
value={endDate}
min="2023-01-01"
max="2030-12-31"
onChange={(event) => setEndDate(event.target.value)}
/>
<div>
*/ <Rendering concert cards> */
</div>
</div>
);
};
export default Explore;
1条答案
按热度按时间vaqhlq811#
当
startDate
或endDate
发生更改时,您可以触发另一个useEffect