我正在尝试使用jQuery库(Highcharts)在React组件中呈现数据。
据我了解,我需要将jQuery代码放在componentDidMount()函数中,以使其正常运行。只要我在componentDidMount()方法中包含静态数据,它就可以做到。
但是我想将jQuery代码连接到我的数据库,以便图表是被动的。我读到componentDidMount()只运行一次,所以我怀疑我在其中放入反应性数据会遇到麻烦(我什至无法获得道具登录到控制台……它们总是未定义)。
我可以将props传递给componentDidUpdate(),但是我的jQuery代码不会显示。
有人有解决办法吗?
谢谢!!
您可以利用.setData
Highcharts提供的方法。您可以在每次收到新道具时更新数据。这是一个非常基本的示例,显示了这一点:
class Chart extends React.Component {
constructor() {
super();
// Init state.
this.state = { chart: {} };
}
componentDidMount() {
const _this = this;
// Init chart with data from props.
var chart = Highcharts.chart('chart', {
series: [{ data: _this.props.data }]
});
// Save the chart "container" in the state so we can access it from anywhere.
this.setState({ chart });
}
componentWillReceiveProps(props) {
// Update the chart with new data every time we receive props.
this.state.chart.series[0].setData(props.data);
}
render() {
return <div id="chart" />;
}
}
class App extends React.Component {
constructor() {
super();
// Set some initial data.
this.state = { data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]};
this.changeData = this.changeData.bind(this);
}
changeData() {
// Update with a different dataset.
this.setState({
data: [129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4],
});
}
render() {
return(
<div>
<button onClick={this.changeData}>Change Data</button>
<Chart data={this.state.data} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="View"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句