useState 除了直接给定初始值,还可以通过函数返回值的形式为状态赋初始值
const [value, setValue] = useState(() => 返回值);
const App: React.FC = () => {
const [count] = useState(() => {
**const date = new Date();
return { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() }**
});
return (
<div>
<h1>Year: {count.year}</h1>
<h1>Month: {count.month}</h1>
<h1>Day: {count.day}</h1>
</div>
);
};
export default App;