reactjs - 未处理的拒绝(TypeError):无法读取 null 的属性“getContext”
问题描述
在我的应用程序中有 3 个页面,分别是登录、注册和仪表板。当我在登录时重定向回仪表板时,出现此错误。 错误出现在一个名为 Sensor Reading Chart SensorReadingChart.js的组件中
class SensorReadingChart extends Component {
_isMounted = false;
chartRef = React.createRef();
constructor(props) {
super(props);
threshold = props.threshold
xAxisLabel = props.xAxisLabel
yAxisLabel = props.yAxisLabel
chartTitle = props.chartTitle
x = props.x
y = props.y
location = props.location
icon = props.icon
apiEndPoint = props.apiEndPoint
yUnit = props.yUnit
themeColor = props.themeColor
this.state = {
sensorReadings:[]
}
}
render() {
dataPoints = this.state.sensorReadings.map(
(sensor) => {
return {
x: sensor[x], //change this to proper key
y: sensor[y], //change this to proper key
location: sensor[location], //change this to proper key
}
});
thresholdLine = this.state.sensorReadings.map(
(sensor) => {
return {
x: sensor.id, //change this to proper key
y: threshold,
}
});
options = {
type: "line",
data: {
xLabels: dataPoints.map(x=>{return x.x}),
datasets: [
{
data: dataPoints.map(y=>{return y.y}), //Sample data set [{x:1, y:21},{x:2, y:25},{x:3, y:31},{x:4, y:11},]
showLine: true,
fill: false,
borderColor: themeColor[1],
label: yAxisLabel+" Graph",
pointBackgroundColor: function(context) {
let index = context.dataIndex;
let value = context.dataset.data[index];
return value > threshold ? themeColor[0] : 'transparent';
},
pointBorderColor: function(context) {
let index = context.dataIndex;
let value = context.dataset.data[index];
return value > threshold ? themeColor[0] : 'transparent';
}
},
{
data: thresholdLine.map(y=>{return y.y}),
showLine: true,
borderColor: themeColor[0],
fill: false,
pointBorderColor: "transparent",
label: "threshold = "+threshold+" "+yUnit
}
]
},
options: {
animation: {
duration: 0
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = yAxisLabel+" : "+tooltipItem.yLabel+" F | "+xAxisLabel+" : "+tooltipItem.xLabel;
if (tooltipItem.yLabel > threshold) {
label += " | Location : "+data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].location //change this to proper key
}
return label;
}
}
},
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: yAxisLabel + " in " + yUnit,
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: xAxisLabel,
},
},
],
},
}
}
if(this.state.sensorReadings.length === 0)
{
return (<h5 className="card-subtitle mb-2 text-muted " align={"center"}><i className="bi bi-lightning"/>No Readings Yet!</h5>)
}
else{
return (
<div>
<div><big><i className={icon} style={{color: themeColor[0]}}/>{chartTitle}</big></div>
<br/>
<canvas
id="myChart"
ref={this.chartRef}
/>
</div>
)}
}
componentDidMount() {
this._isMounted = true;
if(this._isMounted){
SensorService.getSensorReadings(apiEndPoint).then((response)=>{
const sensorReadings = response.data
this.setState({sensorReadings})
const myChartRef = this.chartRef.current.getContext("2d");
new Chart(myChartRef, options);
});
}
}
componentWillUnmount(){
this._isMounted = false;
}
}
export default SensorReadingChart;
所以我想重定向到登录页面而不会出现此错误这是完整的错误
未处理的拒绝(TypeError):无法读取 null(匿名函数)src/components/SensorReadingChart.js:154 的属性“getContext”
152 | const sensorReadings = response.data
153 | this.setState({sensorReadings})
> 154 | const myChartRef = this.chartRef.current.getContext("2d");
| ^ 155 | new Chart(myChartRef, options);
156 | });
157 | }
查看已编译 此屏幕仅在开发中可见。如果应用程序在生产中崩溃,它不会出现。打开浏览器的开发者控制台以进一步检查此错误。单击“X”或按 ESC 以关闭此消息。
解决方案
chartRef = React.createRef();
这
this.chartRef = React.createRef();
添加
...
class SensorReadingChart extends Component {
_isMounted = false;
chartRef = React.createRef(); // <-- HERE!!
constructor(props) {
super(props);
...
基本上,JavaScript 不能像上面那样直接在类下有变量,这会出乎意料地工作。所以上面的行移动:
...
class SensorReadingChart extends Component {
constructor(props) {
super(props);
this._isMounted = false; // <-- WITH IT!!
this.chartRef = React.createRef(); // <-- HERE!!
...
this
问题好麻烦。
为避免this
问题,我强烈推荐功能组件样式,如果您有特殊情况。在功能组件样式中,实例this
总是清晰的。
推荐阅读
- javascript - 将 CSS.supports() 与媒体查询一起使用?
- python - 为什么我的模拟类的实例共享属性?
- python - 在 Pandas 中对匹配多个条件的数据框进行切片
- visual-c++ - 与 irrklang::ISound 一起使用时不会播放 irrklang 声音
- proc-r-package - 我可以使用响应率而不是原始数据作为 ROC 的输入吗?
- python - 如何并行化返回 lambda 的函数
- python - 将 Python 脚本 (DHT22 - CircuitPython) 与 (RPLCD) 结合起来,在 RPi 上的 1602 LCD 上进行温度读数
- swift - 根据字符串返回颜色
- c# - 在运行时修改 appSettings 而不写入磁盘
- java - 未在 PubSub 模拟器中创建主题