触发点击功能之前如何确保参考电流存在?

杰格713

尝试设置canvasRef.current时收到未定义的错误。我尝试了多种方法来形成回调ref,但是我没有走运。在canvasRef.current不是未定义的情况下,如何等待触发onClick函数'handleViewStuff'?

const Child = (props) => {

  const canvasRef = useRef();

  const handleViewStuff = useCallback(() => {
     
    apiCall(id)
      .then((response) => {
        
        // do stuff

        return stuff;
      })
      .then((result) => {

        result.getPage().then((page) => {
        
      const canvas = canvasRef.current; 
      const context = canvas.getContext('2d'); // error is coming in here as getContext of undefined meaning canvas is undefined'

          canvas.height = 650;
          

          const renderContext = {
            canvasContext: context,
           
          };
    
          page.render(renderContext);
        
        
        });
      });

  }, []);

  return (

    <Fragment>

    <canvas ref={(e) => {canvasRef.current = e}} />

        <Button
      
          onClick={handleViewStuff}
        > 
         View Stuff

       </Button>
      
    </Fragment>
  );
};

export default Child;
yun
  1. 使用 if-statement
...
if(canvas.current) {
  const canvas = canvasRef.current; 
  const context = canvas.getContext('2d'); 
}
  1. 使用 optional chaining
...
  const canvas = canvasRef?.current; 
  const context = canvas?.getContext('2d'); 

而且我在您的代码中发现了一些错误。

  1. 添加依赖 useCallback
const handleViewStuff = useCallback(() => {
  ...
}, [canvasRef.current]);
  1. 应该使用ref这样的。
<canvas ref={canvasRef} />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章