React useState 在 Highcharts mouseOver 上抛出错误

React useState throws error on Highcharts mouseOver

我有一个带有 highcharts 图表的 React TypeScript 应用程序。我想根据用户将鼠标悬停在图表的一部分上时获得的数据更新“价格”标签(在 highcart 之外)。

mouseOver 回调工作正常,我可以成功地将我想要的数据记录到控制台。但是,当我尝试使用 setPrice 的 useState 挂钩更新价格状态时,我从 highcharts 收到错误消息。如果我注释掉 setPrice 行,没有错误。有什么想法吗?

Uncaught TypeError: Cannot read properties of null (reading 'yAxis')
    at highstock.src.js:24009
    at Array.forEach (<anonymous>)
    at c.getAnchor (highstock.src.js:23992)
    at c.refresh (highstock.src.js:24517)
    at c.runPointActions (highstock.src.js:27941)
    at c.onContainerMouseMove (highstock.src.js:27502)

这是我如何实现它的一些伪代码:

const [price, setPrice] = useState<number>(0)

options = {
  ...
  plotOptions: {
    series: {
      point: {
        events: {
          mouseOver: function(e:any) {
            price = // logic to fetch price based on mouse position 
            console.log(price)   
            setPrice(price)
          }
        }
      }    
    }
  }
}

和 html(样式组件)

<Price>{ price }</Price>

我的预感是将数据返回给您会有时间延迟。尝试 async/await,然后根据这些结果重新设置您的状态。

数据可能不会立即可用,这就是它返回空数据的原因。但是,您可以像这样使用 setTimeout 延迟异步设置数据。

const [price, setPrice] = useState<number>(0)

options = {
  ...
  plotOptions: {
    series: {
      point: {
        events: {
          mouseOver: function(e:any) {
            price = // logic to fetch price based on mouse position 
            console.log(price)   
            setTimeout(() => { // This is where the delay comes in
            setPrice(price)
            }, 0)
          }
        }
      }    
    }
  }
}