javascript - 如何在每毫秒滴答的 onTick 事件中设置状态

标签 javascript reactjs cesium

我正在尝试在 onTick 事件中为时钟设置状态。

 <Viewer>
   <Clock
        startTime={start.clone()}
        stopTime={stop.clone()}
        currentTime={start.clone()}
        multiplier={50}
        onTick={_.throttle(handleValue, 1000)} // this thing ticks every millisecond
      />
    <Entity
          ref={ref} // here is the ref to get the value I want to set state with
          position={positionProperty}
          tracked
          selected
          model={{ uri: model, minimumPixelSize: 100, maximumScale: 100.0 }}
          availability={
            new TimeIntervalCollection([
              new TimeInterval({ start: start, stop: stop }),
            ])
          }
        />
 </Viewer>

这是handleValue函数。
  const handleValue = (clock) => {
//setting the state here ( I want to display the chaning the value over time) 
  setHeadingValue(ref.current.cesiumElement._properties._heading.getValue(clock.currentTime));
    }
  };

问题是它看起来像是试图一遍又一遍地重新渲染,从而卡住了应用程序。
由于 setState 的性质,这种行为是有意义的。但我觉得有一个答案在逃避我。
我可以对我能做什么有一些了解吗?我没主意了。
我正在使用 Resium(一个 react 库),现在我正在使用 .getElementByID() 设置值并附加到dom ..它首先使用react失败...
这是一个代码沙箱:https://codesandbox.io/s/resium-cesium-context-forked-bpjuw?file=/src/ViewerComponent.js
有些元素没有显示,因为我们需要一个 token ,但这不会影响我正在寻找的功能。只需打开代码沙箱的控制台,进入 ViewerComponent.js
谢谢您的帮助

最佳答案

如我所见,这里的问题不在库中,而是在管理计算和可视化的方式上。
正如少数人已经提到的,对于 UI,用户不需要超过 60fps,但对于进程,有时我们需要更多。
因此解决方案是将处理与可视化分开。
为了更通用,这是一个纯 JavaScript 的示例:

// Here it may be some component 
const clockView = document.getElementById('speedyClock')

let state = null
// This function mimicking dispatch on state update 
function setState(val) {
  state = val
  clockView.innerHTML = state
} 

const FPS = 30


// Any state out of visualization scope
// Not the React state!!!
let history = []

let nextUiUpdate = Date.now()+(1000/FPS) 

/// Super speedy process
setInterval(function() {
  history.push(Math.random())
  const now = Date.now()
  
  // Update according to visual frame rate
  if(now >= nextUiUpdate) {
    // Prepare visual updates
    setState(JSON.stringify({count: history.length, history}, null, 2))
    history = []    
    nextUiUpdate = Date.now()+(1000/FPS)
  }
}, 1)
<pre id="speedyClock"></pre>

关于javascript - 如何在每毫秒滴答的 onTick 事件中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67454286/

相关文章:

javascript - 异步运行 lodash flow 时传递参数

reactjs - 共享组件库最佳实践

javascript - 如何将 tsx 文件转换为 React 的 js 文件

geoserver - 如何为Geoserver WMS在Cesium SandcaSTLe中启用跨源资源共享(CORS)获取请求

javascript - 为什么 MongoDB 查询使用 $gt 和 $lte 而不是 > 和 <=?

javascript - 如何知道溢出元素可见部分的长度?

javascript - 在 Bootbox 模式对话框中使用 Tiny MCE 编辑器

javascript - 当输入被清除时输入值重置

javascript - Cesium:选择实体并检索 WMS 的信息

three.js - Threejs 和 3D Tiles(来自 Cesium)