Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在启动点击功能之前,如何确保ref.current存在?_Reactjs - Fatal编程技术网

Reactjs 在启动点击功能之前,如何确保ref.current存在?

Reactjs 在启动点击功能之前,如何确保ref.current存在?,reactjs,Reactjs,尝试将canvasRef.current设置为当前时,我收到一个未定义的错误。我尝试了许多不同的方法来形成回调引用,但我没有得到任何运气。在canvasRef.current未定义后,如何等待启动onClick函数“handleViewStuff” const Child = (props) => { const canvasRef = useRef(); const handleViewStuff = useCallback(() => { apiC

尝试将canvasRef.current设置为当前时,我收到一个未定义的错误。我尝试了许多不同的方法来形成回调引用,但我没有得到任何运气。在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;
const Child=(道具)=>{
const canvasRef=useRef();
const handleViewStuff=useCallback(()=>{
apiCall(id)
。然后((响应)=>{
//做事
归还物品;
})
。然后((结果)=>{
result.getPage()。然后((页面)=>{
const canvas=canvasRef.current;
const context=canvas.getContext('2d');//此处出现错误,因为未定义意义的getContext canvas未定义'
高度=650;
常量renderContext={
背景:背景,
};
page.render(renderContext);
});
});
}, []);
返回(
{canvasRef.current=e}}/>
查看资料
);
};
导出默认子对象;
  • 使用
    if语句
  • 使用
    可选链接
  • 我在你的代码中发现了一些错误

  • useCallback
  • 应该像这样使用ref
  • 
    
    ...
    if(canvas.current) {
      const canvas = canvasRef.current; 
      const context = canvas.getContext('2d'); 
    }
    
    ...
      const canvas = canvasRef?.current; 
      const context = canvas?.getContext('2d'); 
    
    
    const handleViewStuff = useCallback(() => {
      ...
    }, [canvasRef.current]);
    
    <canvas ref={canvasRef} />