【发布时间】:2019-11-14 07:52:15
【问题描述】:
当我在 image.onload() 中调用 useState() 挂钩时,我遇到了重新渲染 React 组件的问题。我希望组件在我调用setClassificationResult 后重新渲染一次,但由于某种原因,它一直在重新渲染,就像我有一些无限循环一样。这是我的代码:
const ImageClassification = React.memo(function() {
const [isModelLoaded, setModelLoaded] = useState(false);
const [uploadedFile, setUploadedFile] = useState();
const [classifier, setClassifier] = useState();
const [classificationResult, setClassificationResult] = useState();
useEffect(() => {
async function modelReady() {
setClassifier(
await MobileNet.load().then(model => {
setModelLoaded(true);
return model;
})
);
}
modelReady();
}, []);
function onDrop(acceptedFiles: File[]) {
setUploadedFile(acceptedFiles);
}
function prepareImage(inputFile: File) {
const image = new Image();
let fr = new FileReader();
fr.onload = function() {
if (fr !== null && typeof fr.result == "string") {
image.src = fr.result;
}
};
fr.readAsDataURL(inputFile);
image.onload = async function() {
const tensor: Tensor = tf.browser.fromPixels(image);
classifier.classify(tensor).then((result: any) => {
// Crazy re-rendering happens when I call this hook.
setClassificationResult(result);
console.log(result);
});
console.log("Tensor" + tensor);
};
}
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
return (
<React.Fragment>
{!isModelLoaded ? (
<CircularProgress />
) : (
<div {...getRootProps()}>
<input {...getInputProps()} />
{isDragActive ? (
<p>Drop the files here.. </p>
) : (
<p>Drag 'n' drop some files here, or click to select files</p>
)}
{uploadedFile &&
uploadedFile.map((item: File) => {
prepareImage(item);
return classificationResult
? classificationResult.map((result: any) => {
return (
<ClassificationResult
className={result.className}
probability={result.probability}
/>
);
})
: null;
})}
</div>
)}
</React.Fragment>
);
});
export default ImageClassification;
知道如何避免这种疯狂的重新渲染吗?
【问题讨论】:
-
如果您更新状态,组件将重新渲染。你到底想达到什么目的?
-
我希望组件重新渲染一次,但它一直在重新渲染,而不仅仅是一次。我要做的是将分类结果设置为
classificationResult,然后在组件中呈现结果。我也会更新问题。
标签: reactjs typescript react-hooks tensorflow.js