【发布时间】:2020-05-11 19:01:57
【问题描述】:
我有一个非常简单的代码来设置状态变量,但是遇到了麻烦。
https://codesandbox.io/s/highcharts-react-demo-rtlie
我看到 this.state.chart_options 显示在控制台上,但它为空。
代码:_
import React from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
import drilldow from "highcharts/modules/drilldown";
//import HighchartsReact from "./HighchartsReact.js";
import PieChart from "highcharts-react-official";
drilldow(Highcharts);
const options = {
chart: {
type: "pie"
},
series: [
{
data: [{ y: 100, name: "Female" }, { y: 50, name: "Male" }]
}
]
};
class App extends React.Component {
constructor() {
super();
this.state = {
chart_options: null
};
this.setState({ chart_options: options }, () => {
console.log("this.state - ", this.state);
console.log("options - ", options);
});
}
onFilterClickHandler = () => {
console.log("hi", this.state.chart_options);
};
render() {
const key = 1;
return (
<div>
<div>
<label>
<input
type="checkbox"
value={key}
onClick={this.onFilterClickHandler}
/>
</label>
</div>
<h2>Highcharts</h2>
<PieChart highcharts={Highcharts} options={options} />
</div>
);
}
}
render(<App />, document.getElementById("root"));
【问题讨论】:
-
stackoverflow.com/q/34961853/5108962 检查答案,你就会知道哪里出了问题。
-
为什么在 constructor() 中使用 setState ?这是不好的做法!如果要为初始 this.state.chart_option 设置值“options”,则应在声明 this.state.chart_options = options 时设置它的方向。
标签: reactjs