Highcharts-react 在初始页面加载时不呈现

我有一个简单的 React 组件,它应该使用 highcharts-react 库呈现两个 Highcharts。图表的数据来自父组件的状态,并作为道具传递给该组件。当页面加载时,饼图是空的(例如,只有一个没有系列的空圆圈)。如果我使用 React 元素检查器检查 HighchartsReact 元素,我可以看到正确的数据在 options 属性中。此外,如果我手动更改检查器中的任何数据,图表会突然出现。我的猜测是它与图表没有正确更新有关,但我无法准确确定我做错了什么。


const sharedPlotOptions = {

    chart: {

        plotBackgroundColor: null,

        plotBorderWidth: null,

        plotShadow: false,

        type: 'pie'

    },

    title: null,

    tooltip: {

        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'

    },

    plotOptions: {

        pie: {

            allowPointSelect: true,

            cursor: 'pointer',

            dataLabels: {

                enabled: true,

                format: '<b>{point.name}</b>: {point.percentage:.1f} %'

            }

        }

    },

    series: [{

        name: 'Countries',

        colorByPoint: true,

        data: []

    }]

}


export function CountryPopulationPlot(props) {

  let adultData = props.countries.map(country => ({

    name: country.name,

    y: country.population //TODO: use adult only data

  }))


  let allData = props.countries.map(country => ({

    name: country.name,

    y: country.population

  }))


  let adultPlotOptions = sharedPlotOptions

  adultPlotOptions.series[0].data = adultData


  let allPlotOptions = sharedPlotOptions

  allPlotOptions.series[0].data = allData


  return(

    <div>

      <HighchartsReact

        highcharts={Highcharts}

        options={adultPlotOptions}

        oneToOne={true}

      />

      <HighchartsReact

        highcharts={Highcharts}

        options={allPlotOptions}

      />

    </div>

  );

}

编辑: oneToOne 道具是修复错误的尝试,它似乎没有任何效果。


手掌心
浏览 288回答 2
2回答

动漫人物

在 Highcharts 中用于绘制饼图,adultData 和 allData 应采用如下格式:[&nbsp; {&nbsp; &nbsp; name: "USA",&nbsp; &nbsp; y: 1000&nbsp; },&nbsp; {&nbsp; &nbsp; name: "Italy",&nbsp; &nbsp; y: 500&nbsp; }](或者)&nbsp;[&nbsp; {&nbsp; &nbsp; "name": "USA",&nbsp; &nbsp; "y": 1000&nbsp; },&nbsp; {&nbsp; &nbsp; "name": "Italy",&nbsp; &nbsp; "y": 500&nbsp; }]请在您的输入数据中仔细检查。我在 GitHub 上写了一篇博客文章和一个工作应用程序,其中包含一个简单的 Highcharts 饼图示例。请查看: http: //softwaredevelopercentral.blogspot.com/2020/03/react-highcharts-and-spring-boot.html

元芳怎么了

我遇到了同样的问题,并找到了一个粗略的解决方法。就像你说的,这发生在初始组件渲染上。因此通过更新状态触发重新渲染可以解决问题。const [shouldRender, doRender] = useState(true)useEffect(() => {&nbsp; &nbsp;if (shouldRender) {&nbsp; // this stops the cycle after the first re-render&nbsp; &nbsp; &nbsp; doRender(!shouldRender)}想补充一下,以防有人有更好的解决方案,我正在使用相同的道具渲染多个图表,只有饼图是一个问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript