【taro react 错误解决】 ---- Uncaught TypeError: Cannot read properties of null (reading ‘getContext‘)

2022-01-06 16:47:43 浏览数 (1)

1. 错误提示

代码语言:javascript复制
Uncaught TypeError: Cannot read properties of null (reading 'getContext')

2. 错误截图

3. 错误分析

  1. 创建 canvas 的绘图上下文 CanvasContext 对象时canvas还未加载完成;
  2. Taro.createCanvasContext 所放生命周期错误!

4. 解决问题

  1. 错误代码
代码语言: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>
    )
  }
}
  1. 修改后代码
代码语言: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. 总结

  1. 明白每个生命周期,程序执行干了什么;
  2. 有些api需要在对应的生命周期调用!

0 人点赞