【发布时间】:2020-11-15 18:08:01
【问题描述】:
get 请求后,我收到一个对象并通过 props 将其传递给计时器组件,然后在控制台中“警告:收到子元素属性的 NaN。如果需要,将值转换为字符串。 " 在页面上,计时器首先以 NaN: NaN: NaN: NaN 的形式出现,然后才能正常工作
const Lobby = () => {
let {id} = useParams()
const [lobby, setLobby] = React.useState('')
useEffect(() => {
fetch(`${ENDOPOINT}/list/${id}/`, {
method: 'GET',
})
.then((response) => response.json())
.then((data) => {
setLobby(data)
})
}, [])
return (
<PageTemplate>
<div>
<Timer date={lobby.date}/>
}
</div>
</PageTemplate>
)
}
定时器
const Timer = (props) => {
const [timerDays, setTimerDays] = useState('00');
const [timerHours, setTimerHours] = useState('00');
const [timerMinutes, setTimerMinutes] = useState('00');
const [timerSeconds, setTimerSeconds] = useState('00');
useEffect(() => {
const countdownDateFormat = `${props.date}`.split("+")[0]
const countdownDate = new Date(countdownDateFormat).getTime();
const now = new Date().getTime();
const distance = countdownDate - now;
const timer = window.setInterval(() => {
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
if(distance < 0) {
clearInterval(timer)
} else {
setTimerDays(days)
setTimerHours(hours)
setTimerMinutes(minutes)
setTimerSeconds(seconds)
}
}, 1000);
}, [timerSeconds]);
return (
<section className='timer'>
...
</section>
)
}
export default Timer
【问题讨论】:
标签: javascript reactjs