我在项目上使用了Countdown和ReactCodeInput,并且可以正常工作。 但是,当我将其与简单输入结合时,只要我的输入发生更改,它就会重新启动。 我想仅在超时后才重新启动它。这是我的代码:
import React, { Component } from "react";
import Countdown from "react-countdown-now";
import ReactCodeInput from "react-code-input";
const lengthToken = 6;
class Test extends Component {
constructor(props) {
super(props);
this.state = {
token: "",
secondsToExpire: 600000
};
}
saveTokenToState = token => {
this.setState({ token });
};
render() {
const renderer = ({ minutes, seconds }) => (
<span>
{minutes}:{seconds}
</span>
);
return (
<div>
<label htmlFor="token">
<ReactCodeInput
inputmode="numeric"
pattern="[0-9]*"
type="number"
name="test"
fields={lengthToken}
value={this.state.token}
onChange={this.saveTokenToState}
inputStyle={codeStyle}
/>
</label>
<Countdown
renderer={renderer}
date={Date.now() + this.state.secondsToExpire}
/>
</div>
);
}
}
答案 0 :(得分:0)
您正在onChange处理程序中使用setState,这将导致重新渲染。这就是您的倒数计时会重置的原因。我想一种解决此问题的方法是将Countdown放在单独的类中,并扩展React.PureComponent以使其为您处理更新。或者,尽管不建议您在该课程中写自己的shouldComponentUpdate()。
答案 1 :(得分:0)
应用此更改:
import ReactDOM from "react-dom";
import React, { Component } from "react";
import Countdown from "react-countdown-now";
import ReactCodeInput from "react-code-input";
const lengthToken = 6;
class Test extends Component {
countdownDate;
constructor(props) {
super(props);
this.state = {
token: "",
secondsToExpire: 600000
};
this.countdownDate = Date.now() + this.state.secondsToExpire;
}
saveTokenToState = token => {
this.setState({ token });
};
render() {
const renderer = ({ minutes, seconds }) => (
<span>
{minutes}:{seconds}
</span>
);
return (
<div>
<label htmlFor="token">
<ReactCodeInput
inputmode="numeric"
pattern="[0-9]*"
type="number"
name="test"
fields={lengthToken}
value={this.state.token}
onChange={this.saveTokenToState}
/>
</label>
<Countdown renderer={renderer} date={this.countdownDate} />
</div>
);
}
}
答案 2 :(得分:0)
如果您以组件状态保存到期日期,而不是延迟,重新渲染组件不会在Date.now() + secondsToExpire
子级中重新计算Countdown
:
constructor(props) {
super(props);
let date = Date.now() + delay;
this.state = {
token: "",
expirationDate: date
};
}
...
return <div>
...
<Countdown date={this.state.expirationDate} ...>
</div>