javascript - 为什么功能组件中没有声明更新

标签 javascript reactjs typescript

我创建了一个简单的组件,但我在状态更新方面遇到问题。 我知道正确的解决方案,但我的问题是:为什么这段代码不起作用?

import * as React from "react";
import {useEffect, useState} from "react";

type CountdownProps = {
    start: number;
}

export const Countdown: React.FunctionComponent<CountdownProps> = ({start}: CountdownProps) => {
    const [seconds, setSeconds] = useState<number>(start);

    useEffect(() => {
        setInterval(() => setSeconds(seconds - 1), 1000);
    }, []);

    return (<>{seconds}</>);
};

最佳答案

这是 React hooks 的一个已知问题,当涉及到 useInterval 时,Dan 在 Overreacted 的一篇博客文章中谈到了这一问题。

The problem is that useEffect captures the the initial value passed to CountDown initValue from the first render. We never re-apply the effect so the closure in setInterval always references the initValue from the first render, and initValue - 1 is always initValue.

有趣的事实

You can actually check that the interval is actually updating every second by adding a console.log to the statement but it's always getting initValue. Try it out here https://repl.it/repls/MedicalMealyPentagon

有关解决方案,请阅读上面的文章。

关于javascript - 为什么功能组件中没有声明更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613617/

相关文章:

javascript - 圆没有使用 Canvas 正确地通过线连接

arrays - 在处于状态的数组中插入值 - React

reactjs - JSX 的 Typescript 集类型注解

angular - 使用 Angular HTTP Observable 的轮询 API

javascript - React Native 边框半径渲染

javascript - 如何在关闭的弹出窗口中提供(在 IE 和 Firefox 中)二进制文件下载?

javascript - 通过网络浏览器访问 GPU

javascript - 动态导入在 netlify 中不起作用(reactjs)

javascript - 如何在选择器级别和 react native 值中存储js对象?

javascript - 在 JavaScript 中访问 Office UI Fabric 主题颜色