我编写了下面的代码来在我的小型天气应用程序中显示日期。日期显示正确,但在我的脑海里,我有一个想法,我需要尝试编写可重用的代码。如何组合“const date and day”并单独使用它?
import { Weather } from "./type";
import { format } from "date-fns";
import { pl } from "date-fns/locale";
interface Props {
weather: Weather;
}
export default function WeatherApp({ weather }: Props): JSX.Element {
const date = format(new Date(weather.dt * 1000), "LLLL dd, yyyy", {
locale: pl,
});
const day = format(new Date(weather.dt * 1000), "eeee", {
locale: pl,
});
return (
<div className="container-weather">
<div className="container-header">
<h2 className="header">{weather.name}</h2>
</div>
<div className="container-data-forecast">
<p className="data-forecast">
Day: {day.charAt(0).toUpperCase() + day.slice(1)}
</p>
<p className="data-forecast">
{date.charAt(0).toUpperCase() + date.slice(1)}
</p>
</div>
<div className="container-data-forecast">
<p className="data-forecast">
Temprature: {weather.main.temp.toFixed(2)}°C
</p>
<p className="data-forecast">Humidity: {weather.main.humidity}%</p>
</div>
</div>
);
}
我不知道如何做到这一点,因为我还在学习。
只需创建一个返回对象的函数:
interface FormattedDateRecord {
date: string;
day: string;
}
function formattedDate(weather: Weather): FormattedDateRecord {
const localeOptions = { locale: pl };
return {
date: format(new Date(weather.dt * 1000), "LLLL dd, yyyy", localeOptions),
day: format(new Date(weather.dt * 1000), "eeee", localeOptions),
};
}
// ...
const { date, day } = formattedDate(weather);