首页 > 解决方案 > 在 React 中切换会影响 highchart 显示吗?

问题描述

我只是在单击按钮时切换显示值,如下所示:

render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome </h1>
        </header>

        <div id={'container'}>
          <HighchartsReact
            highcharts={Highcharts}
            options={this.state.options}
          />
        </div>

        <button onClick={this.toggleHidden.bind(this)}>More info</button>
      </div>
    );
  }

ToggleHidden 和构造函数定义如下:

constructor(props){
    super(props);
    this.state={isHidden:true,options:{},currentdisplay:{}};
    //this.show= this.show.bind(this);
}

componentDidMount(){
    this.callApi()
    .then(res => this.setState({options:res}))
    .catch(err => console.log(err));
};

toggleHidden () {
    this.setState({
        isHidden: !this.state.isHidden
    })
}

出于某种原因,当我第一次单击按钮时,我的图表会被推高,然后在每次连续单击时它都保持不变。我无法理解这种行为。我的图表的选项是通过调用后端快速服务器来设置的。代码如下:

callApi = async () => {
  const response = await fetch('/api/xdata', {
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  });

  const body = await response.json();
  const response2 = await fetch('/api/ydata', {
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  });
  const body2 = await response2.json();

  const re = JSON.parse(body);

  var re2 = JSON.parse(re2);

  var options = {
    title: {
      text: 'Trying'
    },
    chart: {
      type: 'column'
    },
    xAxis: {
      title: { text: 'xdata' },
      categories: re.xdata
    },
    yAxis: {
      title: {
        text: 'y data'
      }
    },
    series: {
      data: re2.ydata.map(Number)
    }
  };

  if (response.status !== 200) throw Error(body.message);
  return options;
};

标签: javascripthighcharts

解决方案


ReactsetState原因chart.update,你可以在这个例子中检查它:https ://codesandbox.io/s/50p5l109nn

HighchartsReact为避免更新图表,请对包装器添加一些小修改:

componentWillReceiveProps: function() {
  if (this.props.update) {
    this.chart.update(
      Object.assign({}, this.props.options),
      true,
      !(this.props.oneToOne === false)
    );
  }
},

并将updateprops 设置为 false:

    <HighchartsReact
      highcharts={Highcharts}
      constructorType={"chart"}
      options={options}
      update={false}
    />

现场演示:https ://codesandbox.io/s/5256qj19lx


推荐阅读