【问题标题】:How to call a function every time component is displayed?每次显示组件时如何调用函数?
【发布时间】:2020-06-11 20:47:09
【问题描述】:

我是 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 &amp; ReportsPageProps

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    您的内部循环条件和增量是使用 i 而不是 j

    这就是你想要的:

    for (let i = 0; i < props.projects.length; i++) {
          for (let j = 0; j < props.projects[i].tasks.length; j++) {
            setTotalDuration(totalDuration + props.projects[i].tasks[j].totalDurationInSeconds);
          }
    }
    

    【讨论】:

      【解决方案2】:

      useEffect 函数在没有任何依赖关系的情况下使用时,它会执行一次,但您希望totalDuration 在添加任何任务时更新。

         useEffect(() => {
              for (let i = 0; i < props.projects.length; i++) {
                for (let j = 0; j < props.projects[i].tasks.length; j++) {
                  setTotalDuration(totalDuration + props.projects[i].tasks[j].totalDurationInSeconds);
                }
              }
            }, [props.projects])
      

      【讨论】:

        猜你喜欢
        • 2018-08-19
        • 2020-09-06
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多