【发布时间】:2022-11-22 00:20:22
【问题描述】:
在 react-native 中跟随组件:
import { useEffect, useState } from 'react'
let startValue = null // only using this to restart the counter from resetTimer() (other better approaches?)
export const NewTimer = () => {
const [seconds, setSeconds] = useState(startValue)
const formatedTime = () => {
return [pad(parseInt(seconds / 60)), pad(seconds % 60)].join(':')
}
useEffect(() => {
const timer = setInterval(() => setSeconds(++seconds), 1000) // I guess this line triggers the error
return () => {
clearInterval(timer)
}
}, [])
return formatedTime
}
const pad = (num) => {
return num.toString().length > 1 ? num : `0${num}`
}
export const resetTimer = () => {
startValue = 0
}
结果未捕获错误:“秒”是只读的
谁能指出错误在哪里?谢谢!
【问题讨论】:
-
反应状态是只读的。要更新它,请使用您的
setSeconds而不是直接修改它。
标签: javascript react-native readonly