首页 > 解决方案 > 计时器反应 + Redux。React 不要通过 ComponentDidMount 中的计时器(SetInterval)分派动作

问题描述

我正在尝试使用 React + Redux 在我的应用程序中创建一个计时器。所以我有一个组件父级:

import React, { Component } from "react";
import { connect } from "react-redux";
import { compose } from "redux";

import QuestionCounter from "../question-counter";
import FinishButton from "../finish-button";
import TimeCounter from "../time-counter";
import PauseButton from "../pause-button";

import testFinished from "../../actions/test-finished";
import timerTick from "../../actions/timer-tick";
import setTimer from "../../actions/set-timer";

import totalWithEwStruct from "../hoc/total-with-ew-structure";
import withIndicators from "../hoc/with-indicators";

const Total = ({ total, testFinished }) => {
  const { finishedCount, totalCount, isPaussed, timeLeft } = total;
  return (
    <div className="test-total">
      <QuestionCounter
        finishedCount={finishedCount}
        totalCount={totalCount}
        testFinished={testFinished}
      />
      <FinishButton testFinished={testFinished} />
      <TimeCounter
        timeLeft={timeLeft}
        testFinished={testFinished}
        setTimer={setTimer}
        timerTick={timerTick}
      />
      <PauseButton isPaussed={isPaussed} />
    </div>
  );
};

const mapStateToProps = ({ total, loading, error }) => {
  return { total, loading, error };
};

const mapDispatchToProps = {
  testFinished,
  setTimer,
  timerTick
}

export default compose(
  totalWithEwStruct(),
  connect(mapStateToProps, mapDispatchToProps),
  withIndicators()
)(Total);

我尝试在 componentDidMount 中按计时器使用 timerTick

import React, { Component } from "react";

export default class TimeCounter extends Component {
  componentDidMount() {
    const { setTimer, timerTick } = this.props;
    let timer = setInterval(() => {
      timerTick();
      console.log("tick");
    }, 1000);
    setTimer(timer);
  }

  componentDidUpdate() {
    const { timeLeft, testFinished } = this.props;
    if (timeLeft <= 0) {
      testFinished();
    }
  }

  render() {
    const { timeLeft } = this.props;
    return (
      <div className="question-counter__timeleft">
        Времени осталось
        <span className="question-counter__timer">{timeLeft}</span>
      </div>
    );
  }
}

所以我在控制台中看到了“tick”-“tick”-“tick”,但是 React 并没有将我的timerTick()函数分派给 reducer。我已经尝试登录到控制台action.type进行调试,并且没有任何timerTick.

const timerTick = () => {
  return {
    type: "TIMER_TICK"
  };
};

export default timerTick;

它的行动准则。

我不明白为什么它不起作用。

标签: javascriptreactjsreduxreact-redux

解决方案



推荐阅读