使用钩子重构状态
2021-09-17
76
我正在尝试重构具有硬编码初始状态的简单代码,但我对 React Hooks 还不熟悉。
const TimersDashboard = () => {
const [timers, timersChange] = useState(0)
React.state = {
timers: [
{
id: UUID.v4(),
activity: 'Testing activity',
description: 'Lorem ipsum kraf maga',
elapsed: '0',
runningSince: Date.now(),
},
{
id: UUID.v4(),
activity: 'Next activity',
description: 'Lorem ipsum kung fu',
elapsed: '0',
runningSince: Date.now(),
}
]
}
return (
<div className='ui three column centered grid'>
<div className='column'>
<TimersList
timers={this.state.timers}
/>
<NewTimerTool
isOpen={false}
/>
</div>
</div>
);
}
我在使用 Hooks 重写初始状态时遇到了问题。
1个回答
您正在使用功能组件,因此只能使用 Hooks。React.state 仅适用于类组件。 如果您希望初始 React.state 像这样初始化它
const [timers, setTimers] = useState([
{
id: UUID.v4(),
activity: "Testing activity",
description: "Lorem ipsum kraf maga",
elapsed: "0",
runningSince: Date.now(),
},
{
id: UUID.v4(),
activity: "Next activity",
description: "Lorem ipsum kung fu",
elapsed: "0",
runningSince: Date.now(),
},
]);
在 TimersList 中,只需像这样获取 useState 的值
<TimersList timers={timers}/>
。
Proxy
2021-09-17