2022-01-06 16:47:43
浏览数 (1)
1. 错误提示
代码语言:javascript
复制Uncaught TypeError: Cannot read properties of null (reading 'getContext')
2. 错误截图
3. 错误分析
- 创建 canvas 的绘图上下文 CanvasContext 对象时canvas还未加载完成;
- Taro.createCanvasContext 所放生命周期错误!
4. 解决问题
- 错误代码
代码语言:javascript
复制export default class Index extends Component {
componentDidMount () {
this.g2048 = new G2048(this)
}
changeTouchStart(e){
this.g2048.changeTouchStart(e)
}
changeTouchEnd(e){
this.g2048.changeTouchEnd(e)
}
render () {
return (
<View className='index'>
<Canvas canvasId='canvas' className='rui-canvas'
onTouchEnd={this.changeTouchEnd.bind(this)}
onTouchStart={this.changeTouchStart.bind(this)}></Canvas>
</View>
)
}
}
- 修改后代码
代码语言:javascript
复制export default class Index extends Component {
componentDidShow () {
this.g2048 = new G2048(this)
}
changeTouchStart(e){
this.g2048.changeTouchStart(e)
}
changeTouchEnd(e){
this.g2048.changeTouchEnd(e)
}
render () {
return (
<View className='index'>
<Canvas canvasId='canvas' className='rui-canvas'
onTouchEnd={this.changeTouchEnd.bind(this)}
onTouchStart={this.changeTouchStart.bind(this)}></Canvas>
</View>
)
}
}
5. 总结
- 明白每个生命周期,程序执行干了什么;
- 有些api需要在对应的生命周期调用!