我在 setInterval 中使用了 3 个动态变量,
在状态
this.state={
checked: true,
currentHash:"some current hash",
updating: true
}
在 componentDidMount 里面,我做了这样的事情componentDidMount = () => {
let timer
timer = setInterval( (checked, currentHash, updating) => {
try {
this.setState({analysis:true});
if(checked){
var generatedHash = "current generated hash";
if (currentHash !== generatedHash) {
currentHash = generatedHash;
if(updating){
this.setState({updating:false})
const updateResponse = this.props.sendFile(DOCUMENT_ANALYSIS, ""); // my api call
}
else{
this.setState({analysis:false})
}
}
else{
this.setState({analysis:false})
}
clearInterval(timer);
this.componentDidMount();
}
else{
clearInterval(timer);
this.setState({analysis:false});
this.componentDidMount();
}
}
catch (error) {
console.log("Event error", error);
}
}, 10000, this.state.checked, this.state.currentHash, this.state.updating)
}
间隔设置为 10 秒。但是在获得正确的状态数据之前,它调用了两次相同的函数。
最佳答案
你可以试试这个或者你可以试试 react hook 会更好
componentDidMount =()=> {
this.time();
}
time =()=>{
let timer
timer = setInterval( (checked, currentHash, updating) => {
try {
this.setState({analysis:true});
if(checked){
var generatedHash = "current generated hash";
if (currentHash !== generatedHash) {
currentHash = generatedHash;
if(updating){
this.setState({updating:false})
const updateResponse = this.props.sendFile(DOCUMENT_ANALYSIS, ""); // my api call
}
else{
this.setState({analysis:false})
}
}
else{
this.setState({analysis:false})
}
clearInterval(timer);
this.componentDidMount();
}
else{
clearInterval(timer);
this.setState({analysis:false});
this.componentDidMount();
}
}
catch (error) {
console.log("Event error", error);
}
}, 10000, this.state.checked, this.state.currentHash, this.state.updating)
}
关于javascript - api block 被调用 2 次,导致渲染组件两次,但条件得到正确检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65002639/