我正在尝试使用 jQuery 库 (Highcharts) 在 React 组件中呈现数据。
据我了解,我需要将 jQuery 代码放置在 componentDidMount() 函数中才能正确运行。只要我在 componentDidMount() 方法中包含静态数据,就可以了。
但我想将 jQuery 代码连接到我的数据库,以便图表具有反应性。我读到 componentDidMount() 只运行一次,所以我怀疑我在将 react 性数据放入其中时会遇到麻烦(我什至无法获取 Prop 来登录到控制台......它们总是出现未定义)。
我能够将 props 传递给 componentDidUpdate(),但是我的 jQuery 代码不会显示。
谁有解决办法吗?
谢谢!!
最佳答案
您可以使用.setData
Highcharts 提供的方法。每次收到新 Prop 时,您都可以更新数据。这是一个非常基本的示例:
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>
关于javascript - 将 props 传递给 React 组件中的 componentDidMount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110307/