javascript - 计时器反应 + 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;
它的行动准则。
我不明白为什么它不起作用。
解决方案
推荐阅读
- c++ - std::boost::asio::post / dispatch 使用哪个 io_context?
- python - 为什么函数没有返回所需的列表?
- r - R中的文本挖掘和返回命中
- java - TableView 内容不显示
- performance - Teradata 中的易失性表“变量”
- cordova - 为什么在 Visual Studio 2017 中调试 Cordova 应用程序时 DOM Explorer 总是为空?
- mysql - mysql:inner join with in and not in
- unity3d - Speech-To-Text IAM 身份验证连接问题
- arrays - 如何将 ID 和输入数组添加到我的状态?
- python - 当我使用 python 执行 SQL proc 时,它没有完全执行