3

我正在使用 ml5.js 来训练 ML 模型。我必须使用网络摄像头将图像添加到模型中。train 函数适用于当前代码。但是,当我尝试在train函数内的 if else 语句中设置状态时,当我尝试使用测试按钮对其进行测试时会引发错误。

的值classifier变为undefined

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 可以在这里使用,但我不知道如何。

const classifier = useRef()
classifier.current

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

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

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

4

2 回答 2

2

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

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

改为:

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

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

于 2021-04-25T22:19:42.357 回答
1

我会做:

const { current: heap } = useRef({});

// In your `setup`
heap.classifier = featuresExtractor.classification(..);

// elsewhere access it as
heap.classifier

当你写道:

const classifier = useRef()
classifier.current

classifier.current在重新渲染中是持久的,但您仍然需要在设置中将其指定为classifier.current = .... 我更喜欢我写的方式,因为heap它可以方便地添加任何其他应该在重新渲染中保持不变的东西。

于 2021-04-25T18:21:49.047 回答