useRef:渲染后状态变为未定义

时间:2021-04-22 21:45:31

标签: javascript reactjs typescript react-hooks ml5

我正在使用 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

2 个答案:

答案 0 :(得分:2)

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

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

改为:

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

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

答案 1 :(得分: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 是一个方便的地方,可以添加任何其他内容,这些内容应该在重新渲染时保持不变。