highcharts 为什么 prop 更新后没有回调?

9avjhtql  于 5个月前  发布在  Highcharts
关注(0)|答案(1)|浏览(51)

我正在尝试实现加载器的行为。
我有一个代码:

import { DonutChart } from './donut-chart';
const ParentComponent = () => {

    const [isLoading, setIsLoading] = useState(true); // POINT#1

    useEffect(() => {
        // .... some logic to call API and load some data for a chart
        setIsLoading(false) // POINT#2
    }, []);

    return <DonutChart isLoading={isLoading} {...args} />
}

字符串
//donut-chart.jsx

// import ... from modules
highchartsMore(Highcharts);
addExportingModule(Highcharts);
addExportData(Highcharts);
accessibilityModule(Highcharts);
noDataModule(Highcharts);

const DonutChart = ({ isLoading, ...rest}) => {
const options = {...}; // some options from Highcharts API

console.log("POINT#3", isLoading);

return (
    <HighchartsReact
        highcharts={Highcharts}
        options={options}
        update={isLoading}
        callback={instance => { // POINT#4: Here could be the problem
            if (isLoading) {
                console.log('case 1', isLoading);
                instance.showLoading(getCustomLoader());
            } else {
                console.log('case 2', isLoading);
                instance.hideLoading();
            }
        }}
    />
)


getCustomLoader -是一个注入一些自定义样式的动画加载器的函数。在我们的例子中,这是一个圆形,如材质

const getCustomLoader = () => {
    const hasStyles = document.getElementById('custom-loader-styles');
    const innerStyles ='some styles'
    const element = hasStyles || document.createElement('style');

    element.setAttribute('id', 'custom-loader-styles');
    element.innerHTML = innerStyles;
    document.head.appendChild(element);

      return `
      <svg class="custom-loader" viewBox="22 22 44 44">
          <circle class="custom-loader__circle" cx="44" cy="44" r="20.2" fill="none" stroke-width="3.6"></circle>
      </svg>
  `;
}

预期行为

POINT#1:isLoading = true,POINT#3中的console.log显示为true,加载器可见
POINT#2:调用了setIsLoading,isLoading变为“false”
POINT#3:console.log显示:“POINT#3”,false
POINT#4:DonutChart中的Props应该更新,回调也应该更新。在回调中,我的“case 2”应该隐藏loader。

实际行为

POINT#4:DonutChart中的Props已更新,但回调未更新,并且“case 1”仍显示加载器。
不明白为什么会这样。

wlwcrazw

wlwcrazw1#

这是预期的行为。如果immutable选项被禁用,则回调仅被触发一次。在Highcharts API中,我们可以读取:
当图表已加载并且所有外部图像都已加载时运行的函数。定义chart.events.load处理程序是等效的。
使用useEffect钩子或render图表事件来处理加载程序。

useEffect(() => {
  // handle the loader
}, [isLoading]);

字符串

示例:https://codesandbox.io/p/sandbox/highcharts-react-demo-forked-z25gj6
API引用:

https://api.highcharts.com/class-reference/Highcharts.Chart#Chart
https://api.highcharts.com/highcharts/chart.events.redraw

**网址:**https:github.com/highcharts/highcharts-react#options-details

相关问题