Javascript 来自React组件的AJAX请求
我有一个反应组件,看起来像这样。它在内部使用highcharts react来呈现图表,方法是通过向API提供一些状态属性从API获取数据Javascript 来自React组件的AJAX请求,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,我有一个反应组件,看起来像这样。它在内部使用highcharts react来呈现图表,方法是通过向API提供一些状态属性从API获取数据 export default class CandlestickChart extends React.Component { constructor (props) { super(props); this.state = { apiParam1: this.props.propData.p
export default class CandlestickChart extends React.Component {
constructor (props) {
super(props);
this.state = {
apiParam1: this.props.propData.param1,
apiParam2: this.props.propData.param2,
chartConfig: this.getChartConfig(this.props.apiParam1),
};
}
componentDidMount() {
this.renderChart();
}
render() {
return (
<div className='col-lg-6'>
<div className='well'>
<ReactHighStock config={this.state.chartConfig} />
</div>
</div>
);
}
renderChart() {
var that = this;
NanoAjax.ajax({
url: 'myApi.com?param1=' + this.state.apiParam1 + '¶m2=' + this.state.apiParam2;
}, function (statusCode, responseText) {
//transform the data a bit
var chartConfig = that.getChartConfig(that.state.apiParam1);
chartConfig.series[0].data = chartData;
that.setState({
chartConfig: chartConfig
})
});
}
getChartConfig(param1) {
// returns HighCharts chartConfig object based on apiParam1
}
}
导出默认类CandlestickChart扩展React.Component{
建造师(道具){
超级(道具);
this.state={
apiParam1:this.props.propData.param1,
apiParam2:this.props.propData.param2,
chartConfig:this.getChartConfig(this.props.apiParam1),
};
}
componentDidMount(){
这个.renderChart();
}
render(){
返回(
);
}
renderChart(){
var=这个;
NanoAjax.ajax({
url:'myApi.com?param1='+this.state.apiParam1+'¶m2='+this.state.apiParam2;
},函数(状态代码,响应文本){
//稍微变换一下数据
var chartConfig=that.getChartConfig(that.state.apiParam1);
chartConfig.series[0].data=chartData;
那是一个州({
chartConfig:chartConfig
})
});
}
getChartConfig(参数1){
//基于apiParam1返回HighCharts chartConfig对象
}
}
只要组件是静态的,也就是说,一旦在初始渲染期间设置了参数,父控件就永远不会更新它。此外,该方法与此处给出的方法相同:
但是,我的要求是,父控件可以更新此控件的propsparam1
和param2
,使其使用这些值进行新的ajax调用,并使用新数据重新呈现图表
如何处理此问题?您的解决方案仅在安装组件后才会呈现图表
componentDidMount() {
this.renderChart();
}
而要求将图表重新提交一次param1
和param2
更改。为此,我们可以使用,其中您将比较值并相应地采取行动
componentWillReceiveProps(nextProps) {
let shouldRerenderChart = false;
shouldRerenderChart = shouldRerenderChart || this.props.propData.param1 !== nextProps.propData.param1;
shouldRerenderChart = shouldRerenderChart || this.props.propData.param2 !== nextProps.propData.param2;
if (shouldRerenderChart) {
this.renderChart();
}
}
另外,保留componentDidMount函数,因为
React不调用组件将在安装过程中使用初始道具接收道具
作为一种替代方法,您可以使用类似的方法。但是我可以从
组件WillReceiveProps
调用renderChart
,因为通常包含的函数将不允许从其调用堆栈调用setState
?组件WillReceiveProps正是您想要调用setState和它的地方不会触发双重重新渲染,请参阅官方文档:在装入的组件接收新道具之前调用componentWillReceiveProps()。如果需要更新状态以响应道具更改(例如,重置道具),可以比较this.props和nextProps,并在此方法中使用此.setState()执行状态转换。明白了,现在就尝试:)非常感谢,这就是解决方案:)