React JS,如何只允许组件每秒更新一次

React JS, How to only allow component to update once per second

我无法限制组件的更新频率。 组件 A 有一个父组件 B。

我想让组件 A 每秒只更新一次,因为我们使用套接字 IO 来更新实时结果,但是当有 100 个用户时,我们得到的更新太多,页面呈现的方式比我们预期的要多就像给我们一个小故障的外观,因为条形图非常快速地上升和下降。

有没有办法只允许组件 A 每秒更新一次? 我们是否必须控制组件 B 将 props 传递给组件 A 的频率?

您正在寻找的是 节流 ,这将允许函数根据您的要求最多每秒 运行 一次。

我应该在哪里节流?

原则是限制任何会触发 container 组件(承载成为演示组件道具的状态的组件)中的那些状态的突变,而不是限制渲染本身。

如果我在 presentation 组件中节流,现在我希望被节流的所有视图都需要更改为 "throttled components",并且这些不能再是纯功能性的 presentation 组件。

用于演示的可重用组件不需要,甚至不必知道节流。使用它们的容器决定节流和其他行为。仅因为实时提要才需要节流,因此它应该存在于容器处理提要的位置,并且在不影响应用程序其余部分结构的情况下限制在那里。

遵循这一原则,可以从一个地方禁用或修改节流。而且容器中不会有不必要的状态突变,最终会被 "throttled components" 限制。

不太重要的实现细节

你可以自己实现,或者使用像 Lodash 这样的库来实现节流(除其他外)。

您可以使用 throttle 来限制会在 Component A

上触发渲染的状态更新

_.throttle(func, [wait=0], [options={}])

Creates a throttled function that only invokes func at most once per every wait milliseconds.

所以对你来说 func 是触发状态更新的函数,wait 是 1000。(1000 毫秒是 1 秒)

您可以使用 shouldComponentUpdate 并将上次更新时间存储在变量中,然后将现在与上次更新时间进行比较。

class MyComponent extends Component {
    constructor() {
        this.lastUpdateDate = new Date();
    }

    shouldComponentUpdate() {   
        const now = new Date();  
        var seconds = (now.getTime() - this.lastUpdateDate.getTime()) / 1000;   
        return seconds >= 1;   
    }

    componentDidUpdate() {     
        this.lastUpdateDate = new Date();  
    } 

    render() {
        return <span>My Component</span>;
    }
}