javascript - 在 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;
};
解决方案
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)
);
}
},
并将update
props 设置为 false:
<HighchartsReact
highcharts={Highcharts}
constructorType={"chart"}
options={options}
update={false}
/>
推荐阅读
- android - Kotlin Room Cooroutines 从查询返回值
- video - 在 android 或 windows10 中的 10 分钟视频上嵌入水印的最快方法?
- aws-lambda - 如何扩展 DynamoDB 记录处理?
- vue.js - 从 vue-tables-2 获取过滤后的行数组
- r - SAP Analysis for Microsoft Office & R - 如何将 SAP 数据直接提取到 R 中?
- django - 姜戈 + 金贾。无法选择字典的元素
- grails - springSecurityService.isLoggedIn() 在 @MessageMapping 函数中返回 false
- java - 在本地应用程序中使用 AOSP 中已弃用的类
- vue.js - 在 VueJS 和 VueI18n 运行时动态加载翻译
- android - android 中的 Html.fromHtml 是否仅适用于显示的文本?