我是 React 的新手,正在做一个项目以更好地掌握它的所有概念。我目前正在构建一个时间跟踪应用程序,它允许用户跟踪来自不同项目的任务的时间。
我正在使用 Redux 并在我的应用程序状态中存储一个列表,Projects每个列表都有一个Tasks. 每个任务都有一个totalDurationInSeconds属性。
我想创建一个报告页面。目前在报告页面上,我只想显示所有项目的总持续时间(以秒为单位)。当我第一次启动应用程序时,时间为 0。如果我向其中一个项目添加任务,时间会更新。
但是,当我向同一个项目或不同项目添加第二个任务时,该值不会更新,它仍然只显示第一个任务的持续时间。
const ReportsPage: React.FC<Props> = (props): React.ReactElement => {
const [totalDuration, setTotalDuration] = useState(0);
useEffect(() => {
for (let i = 0; i < props.projects.length; i++) {
for (let j = 0; i < props.projects[i].tasks.length; i++) {
setTotalDuration(totalDuration + props.projects[i].tasks[j].totalDurationInSeconds);
}
}
}, [])
return (
<div>
<p>Total time spent across all projects : {totalDuration}</p>
</div>
);
};
我的组件连接到 ReduxStore 并且Props类型为StateProps & ReportsPageProps.