【发布时间】:2020-05-27 05:14:29
【问题描述】:
我正在尝试使用 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;
它的行动准则。
我不明白为什么它不起作用。
【问题讨论】:
-
动作没有被调度,因为在
Total组件中,您正在传递导入的方法timerTick。您只是在创建操作而不是调度它。您可以尝试在Total组件中将道具timerTick而不是导入的timerTick传递给TimeCounter吗?
标签: javascript reactjs redux react-redux