我的子级组件是 HighchartsReactNative 组件 RatingsChart ,它从其父级派生道具。代码是这样的:
import React, { Component } from 'react';
import HighchartsReactNative from '@highcharts/highcharts-react-native';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
ActivityIndicator,
} from 'react-native';
import { WebView } from 'react-native-webview';
import { COLORS } from '../../utils/Constants';
export default class RatingsChart extends Component<{}> {
constructor(props) {
super(props);
console.log("plot on chart: ", this.props.dataToPlot)
console.log("Cats on chart: ", this.props.catsToShow)
var CATS = this.props.catsToShow
this.state = {
freshData: this.props.dataToPlot,
chartOptions: {
chart: {
type: 'bar',
height: '48%',
width: 320
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: CATS,
title: {
text: null
},
labels: {
align: 'left',
reserveSpace: true
},
style: {
fontWeight: 'bold',
fontSize: '40px',
},
visible: true,
lineWidth: 0
},
yAxis: {
min: 0,
title: {
text: '',
align: 'high'
},
style: {
fontSize: 10
},
labels: {
overflow: 'justify',
enabled: false,
},
gridLineWidth: 0
},
tooltip: {
valueSuffix: 'units'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
groupPadding: 0,
pointPadding: 0
},
pointWidth: 6,
}
},
legend: {
enabled: false,
layout: 'horizontal',
align: 'right',
verticalAlign: 'right',
x: -30,
y: 0,
floating: true,
borderWidth: 1,
backgroundColor:
'#cccccc',
shadow: true
},
credits: {
enabled: false
},
series: this.props.dataToPlot
}
};
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.dataToPlot !== nextState.freshData) {
return true
} else return false
}
componentDidMount() {
this.setState({
freshData: this.props.dataToPlot
})
}
render() {
return (
<View>
<HighchartsReactNative
styles={styles.container}
options={this.state.chartOptions}
oneToOne={true}
updateArgs={[true]}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#43AAcc',
justifyContent: 'center',
// width: '80%'
}
});
但是只要道具 dataToPlot
更改,它就不会重新渲染。我已经包含了选项oneToOne={true}
和updateArgs={[true]}
(如highcharts-react-official rendering issue with React state和HighCharts not updating when the state changes in React中的建议,但未达到预期的结果。每次我都必须更新新的在this.state.chartOptions.series
的新值更新后(通过道具this.props.dataToPlot
)绘制图表,我必须重新保存组件 RatingsChart.js 文件。