javascript - 为什么使用 React Hooks、MomentJS 对象和间隔/超时更新状态不会触发重新渲染?

标签 javascript reactjs react-native react-hooks

我正在尝试使用 React-Native、React Hooks、MomentJS 和 (setTimeout/setInterval) 制作一个倒计时器。无论我尝试使用什么方法,它都会失败。问题是组件永远不会重新渲染。

我尝试遵循官方的 React Hooks 文档,Medium 上的几篇文章,例如 The Iceberg of React Hooks但没有任何效果。

一种可能性是它需要 MomentJS 对象的深度克隆,但我认为这是一种低效的方法。

这是我尝试过的可重现的示例之一。

const Timer = () => {
  const [time, setTime] = useState(moment.duration(30, 'seconds'))
  const intervalRef = useRef()

  useEffect(() => {
    intervalRef.current = setTimeout(() => {
      setTime(prevTime => prevTime.subtract(1, 'second'))
    }, 1000)

    return () => {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
  })

  return (
    <View>
      {time.asSeconds()}
    </View>
  )

最佳答案

你是对的,它不会重新渲染,因为你的时刻对象在每次更新时都是相同的(但发生了变化)。您可以通过在 setTime 更新程序中添加 .clone() 轻松使其工作:

const Timer = () => {
  const [time, setTime] = useState(moment.duration(30, "seconds"));
  const intervalRef = useRef();

  useEffect(() => {
    intervalRef.current = setTimeout(() => {
      setTime(prevTime => prevTime.clone().subtract(1, 'second'))
    }, 1000)

    return () => {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
  })

  return <div>{time.asSeconds()}</div>;
};

此处的工作沙箱:https://codesandbox.io/s/gifted-euler-e8xg5

关于javascript - 为什么使用 React Hooks、MomentJS 对象和间隔/超时更新状态不会触发重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728968/

相关文章:

javascript - 可枚举是什么意思?

javascript - Angular Service Worker,缓存离线应用程序的api调用

javascript - 如何监控for循环?

javascript - 阻止组件加载后显示警报 `swal` (sweetalert)

javascript - ReactJS,尝试从 JIRA 的 REST API 获取 JSON 数据,但无法这样做。

reactjs - ReactJS 网站是否符合 WCAG 规定?

javascript - 从 ReactJS 应用程序调用 CMD 命令行

javascript - React JS 中在特定 Prop 更改时调用组件方法的正确模式是什么?

ios - Expo 应用程序因react-native-google-mobile-ads 崩溃 [app.json 中的 react-native-google-mobile-ads 键中未找到 ios_appd_id 键]

ios - 'undefined' has no propType for native prop error react native