UseState没有更新组件属性



我正在做一个项目,我正在玩一个react-count - cycle -timer和useState。我试图添加一个按钮来启动/停止,我想当我停止倒计时重置到初始值。然而,停止发生了,但时间没有重置,除非我导航到另一个项目并返回。我是react的新手,我对useEffect和useState的工作原理没有完全的了解。请帮帮我。谢谢你。

import { Card, Col, Row } from "react-bootstrap";
import { CountdownCircleTimer } from "react-countdown-circle-timer";
import { useEffect, useState } from "react";
const formatRemainingTime = (time) => {
const minutes = Math.floor((time % 3600) / 60);
let seconds = time % 60;
if (seconds < 10 && seconds > -1) {
seconds = `0${seconds}`;
}
return `${minutes}:${seconds}`;
};
const renderTime = ({ remainingTime }) => {
return (
<div className={classes.timer}>
<div className={classes.text}>Remaining</div>
<div className={classes.value}>{formatRemainingTime(remainingTime)}</div>
<div className={classes.text}></div>
</div>
);
};
function MainItem(props) {
const [totalDuration, setTotalDuration] = useState(0);
const [timerOn, setTimerOn] = useState(false);
useEffect(() => {
const myDuration =
parseInt(props.item.red.split(":")[0]) * 60 +
parseInt(props.item.red.split(":")[1]) +
30;
setTotalDuration(myDuration);
}, [props]);
const startHandler = () => {
setTimerOn(true);
};
const stopHandler = () => {
setTimerOn(false);
};
const resetHandler = () => {
setTimerOn(false);
setTotalDuration(totalDuration)
};
return (
<Row>
<Col>
<Card>
<Card.Body>
<Row>
<Col>
<div>
<button onClick={startHandler}>Start</button>
<button onClick={stopHandler}>Pause</button>
<button onClick={resetHandler}>Reset</button>
</div>
</Col>
<Col className={classes.timer_wrapper}>
<CountdownCircleTimer
key={totalDuration}
isPlaying={timerOn}
duration={totalDuration}
size={300}
strokeWidth={20}
trailColor={"#363537"}
colors={[
["#42b0f5", 0.5],
["#42b0f5", 0.01],
["#2bb32b", 0.2],
["#2bb32b", 0.01],
["#eeee60", 0.2],
["#eeee60", 0.01],
["#ff4a2e"],
]}
onComplete={() => [true, 1000]}
>
{renderTime}
</CountdownCircleTimer>
</Col>
</Row>
</Card.Body>
</Card>
</Col>
</Row>
);
}
export default MainItem;

React可以意识到,您实际上没有更改totalDuration。因此,不会触发任何事件来更新CountdownCircleTimer中的密钥道具。您应该创建另一个键,如

const [key, setKey] = useState(false)
...
<CountdownCircleTimer key={key} ... />

重置定时器的函数为

const reset = () => setKey(val => !val)

这样,每次调用reset()时,val都会发生变化,因此触发key的更新。

@vektor-hector,谢谢。浪费了太多时间去解决同样的问题。有很多解决方法,但没有比你的更容易。顺便说一下,其他的解决方案对我没有帮助。

<CountdownCircleTimer
key={key}
isPlaying={key}
duration={duration}
size={75}
colors={["#004777", "#F7B801", "#A30000", "#A30000"]}
colorsTime={[50, 30, 15, 0]}       

onComplete={(totalElapsedTime) => {          
setKey(prev => !prev);
showConfirmDialog();
return { shouldRepeat: true, delay: 1} 
}}
updateInterval={1}        
>
const showConfirmDialog = () => {
return Alert.alert(
"Are you sure",        
[
// The "Yes" button
{
text: "Yes",
onPress: () => { 
setKey(prev=>!prev);
},
},
{
text: "No",
onPress: () => {
navigation.navigate('FirstPage');
},
},
]
);
};

相关内容

  • 没有找到相关文章

最新更新