reactjs - React 原生 setInterval useState

标签 reactjs react-native react-hooks setinterval use-state

我正在创建间隔计数器,下面的代码工作正常。但我对这段代码有几个我不理解的问题。

import React, { useState, useEffect } from 'react';
import {View, Text} from 'react-native'

const Interval = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      console.log(`seconds: ${seconds}`)
      setSeconds(seconds => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
      <View>
        <Text>
          {seconds} seconds have elapsed since mounting.
        </Text>
      </View>
  );
};

export default IntervalExample;
  1. 如果我输入setSeconds(seconds => seconds + 1);,为什么这不起作用?相反 setSeconds(seconds + 1);更简单吗?
  2. 为什么 console.log(`seconds: ${seconds}`)始终记录为 0

最佳答案

要运行useEffect,您需要传递变量作为第二个参数(在您的例子中,它是)。当此变量更改时,useEffect 将再次运行。

来自文档:

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often. Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.

也就是说,您需要将第二个变量传递给 useEfect:

useEffect(() => {...}, [seconds])

在这种情况下,您可以使用 setSeconds(seconds + 1); 而不是传递函数。

完整代码:

useEffect(() => {
 const interval = setInterval(() => {
   console.log(`seconds: ${seconds}`)
   setSeconds(seconds + 1)
  }, 1000)
 return () => clearInterval(interval)
}, [seconds])

关于reactjs - React 原生 setInterval useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67803897/

相关文章:

javascript - 何时使用 React 错误边界组件?

android - 如何阅读 Crashlytics?

android - 如何在 React Native 应用程序中添加圆形底部可折叠工具栏?

javascript - React Native Undefined 不是一个对象(评估'userData.id)

reactjs - 将 HOC 与 React Hooks 一起使用仍然有意义吗?

javascript - 在重新加载时删除标记时,react-native-maps 中的 callout View 不会消失

javascript - React : Uncaught TypeError: this. state.data.map 不是一个函数并且

javascript - React/Redux - 如何渲染/更新深度嵌套状态

javascript - React hook useEffect() 底层。使用 useEffect 安排的效果是否会阻塞主线程?

reactjs - 使用 React Hooks 更新值