@chudomozg

Таймер на React + Redux. React не передает экшн в редюсер по таймеру, что не так?

Я пытаюсь сделать таймер в моем приложении (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);


Я пытаюсь использовать timeTick в таймере (setInterval) в componentDidMount

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" в консоли, но реакт не диспатчит мой timerTick() в редюсер.
Я пробывал выводить action.type со всех поступающих экшнов в консоль, но моего события не приходит.

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

export default timerTick;


Выше код кэкшна. Я не знаю почему это не работает, может кто-нибудь хотя бы подскажет куда копать?
  • Вопрос задан
  • 593 просмотра
Решения вопроса 1
@chudomozg Автор вопроса
Проблема оказалась в том, что компонент Total подтягивал timerTick напрямую из экшкриэтора. Я забыл указать timerTick в дестуктуризации props. Меня смутило то, что когда я выводил в консоль timerTick из пропс TimeCounter - он был не underfined. Но я не обратил внимание, что это была просто функция.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы