【问题标题】:react-native state is read-onlyreact-native 状态是只读的
【发布时间】: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


【解决方案1】:

当你做++seconds时,你正试图改变seconds这个渲染,这是不允许的。我会使用 setState 回调来获取当前值,然后执行 seconds + 1,这将完成同样的事情:

useEffect(() => {
  const timer = setInterval(() => setSeconds((seconds) => seconds + 1), 1000)
  return () => {
    clearInterval(timer)
  }
}, [])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2020-07-19
    • 2019-03-02
    • 1970-01-01
    • 2017-10-28
    • 2018-08-02
    相关资源
    最近更新 更多