useRef:渲染后状态变为未定义 [英] useRef: state becomes undefined after rendering

查看:104
本文介绍了useRef:渲染后状态变为未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ml5.js 来训练 ML 模型.我必须使用网络摄像头向模型添加图像.train 函数在当前代码下运行良好.但是,当我尝试在 train 函数内的 if else 语句中设置状态时,当我尝试使用测试按钮测试它时会抛出错误.>

classifier 的值变为 undefined.

I'm using ml5.js to train an ML model. I have to add images to the model using the webcam. The train function works fine with the current code. However, when I try to set a state within my if else statement inside the train function, it throws an error when I try to test it using the test button.

the value of classifier becomes undefined.

</div>);};

export const Component: React.FC<ComponentProps> = (props: ComponentProps) => { let classifier: any; classifier = featureExtractor.classification(capture, videoReady); } function final() { classifier.classify(capture, (error, result) => { setPrediction(label); }); } return (<div> <Button variant="contained" color="primary" onClick={() => final()}>testing!</Button> </div> </div>) ; };

classifier 是一个变量,因此每次都会重新渲染.useRef 可以在这里使用,但我不知道如何使用.

classifier is a variable so it would re-render each time. useRef could be used here but I couldn't figure out how.

const classifier = useRef()
classifier.current

像这样访问它仍然给我错误.我还尝试为分类器本身创建一个状态,但这对我来说似乎也不起作用.

accessing it like this still gave me the error. I also tried making a state for the classifier itself but that did not seem to work for me either.

这是一个 Codesandbox 来尝试完整的东西.要查看错误,可以在train函数的if else语句中设置一个状态:

Here's a Codesandbox to try the full thing. To see the error, you can set a state in the if else statement of the train function:

https://codesandbox.io/s/hardcore-solomon-zb34l?file=/src/Component.tsx

推荐答案

我提供了上面评论中提到的 Codesandbox 的分叉版本:https://codesandbox.io/s/frosty-sea-0pcfx?file=/src/Component.tsx.这包含一些修复,但大部分与更改 captureclassifier 的局部变量并将它们分配给 refs 相关.以下代码:

I've provided a forked version of the Codesandbox that was mentioned above in the comments: https://codesandbox.io/s/frosty-sea-0pcfx?file=/src/Component.tsx. This contains a few fixes, but most of it related to changing the local variables for capture and classifier and assigning them to refs. The following code:

let capture: p5Types.Element;
let classifier: any;

改为:

let capture: any = useRef<any>();
let classifier: any = useRef<any>();

然后在代码的其他区域对这些变量的所有引用都切换到 capture.currentclassifier.current.这些也可能存储在状态中,但它们似乎只在渲染期间使用的数据之外分配和使用,并且不需要组件在分配时重新渲染.

Then all references to those variables in the other areas of the code were switched to capture.current and classifier.current. Those could potentially be stored in state as well, but they appear to only be assigned and utilized outside of data used during rendering and don't require the component to re-render whenever they are assigned.

这篇关于useRef:渲染后状态变为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆