0

我的 React 应用程序有问题:当某个变量 ( repetitions) 超过阈值时,我需要有条件地在屏幕上呈现一个 Button。

该变量被更新到componentDidMount()函数中,该函数从网络摄像头检索视频并根据它在视频上检索到的内容更新上述变量:

export default class Recognizer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      repetitions : 0,
      max_repetitions : 15
    };
  }

  componentDidMount(){
    const videoElement = document.getElementsByClassName('input_video')[0];
    const canvasElement = document.getElementsByClassName('output_canvas')[0];
    const canvasCtx = canvasElement.getContext('2d');

    function onResults(results) {
      canvasCtx.save();
      canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
      canvasCtx.drawImage(results.image, 0, 0, canvasElement.width, canvasElement.height);
      
      var point;
      var sample = [];

      for (point = 0; point < results.poseLandmarks.length; point++) {
         sample.push(results.poseLandmarks[point].x*canvasElement.width)
         sample.push(results.poseLandmarks[point].y*canvasElement.width)
         sample.push(results.poseLandmarks[point].z*canvasElement.width)
        }

      let result=predict(sample) //some kind on ML in "predict" function 
      
      if (result==1) {
         repetitions=repetitions+1 // <-- I should update this.state.repetitions here but I cannot access "this"
        }

      canvasCtx.restore();
    }

    const pose = new Pose({locateFile: (file) => {
      return `https://cdn.jsdelivr.net/npm/@mediapipe/pose@0.3.1620325689/${file}`;
    }});
    pose.onResults(onResults);

    const camera = new Camera(videoElement, {
      onFrame: async () => {
        await pose.send({image: videoElement});
      },
      width: 1280,
      height: 720
    });
    camera.start();

  }

  render() {
    return (
      <div className="Home">
        <div className="lander">

        <div className="App">
            <video hidden className="input_video"></video>
            <canvas className="output_canvas" width="1280px" height="720px"></canvas>
        </div>
        
        {this.state.repetitions > this.state.max_repetitions ? <form><Button className="btn-action">Continue</Button></form>: null }
  
        </div>
      </div>
    );
  }
}

正如您在代码中看到的,有一个onResults函数 intocomponentDidMount()有没有办法从那里访问状态变量?

谢谢你。

4

0 回答 0