gpt4 book ai didi

reactjs - 子组件在父组件重新渲染时重新渲染,即使 React.memo 返回 true

转载 作者:行者123 更新时间:2023-12-04 03:46:59 25 4
gpt4 key购买 nike

我有一个嵌套组件,它启动用于上传图像的 HTTP 请求。它显示进度。

const PreviewItem = React.memo(function PreviewItem(props: PreviewItemProps) {
const {fileObject, handleRemove, classes, onUploadFinished} = props

const [isLoading, setIsLoading] = useState(false)
const [completed, setCompleted] = useState(0);

const cancelTokenSource = axios.CancelToken.source();

useEffect(() => {
const data = new FormData();
data.append('file', fileObject.file);

const config: AxiosRequestConfig = {
onUploadProgress: function (progressEvent) {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setCompleted(percentCompleted)
},
cancelToken: cancelTokenSource.token
};

if (!fileObject.isUploaded) {
setIsLoading(true)
avantiApi.post<DirectUploadResponse>("images/upload", data, config).then(response => {

setIsLoading(false)

if (onUploadFinished) {
onUploadFinished(response.data, fileObject)
}
}).catch(e => console.log("Upload Error", e))
}
return function abortUpload() {
console.log("Use effect...aborting...")
cancelTokenSource.cancel("Cancelled")
}
}, [fileObject])

return <> ..... </>
}, function (prevProps: Readonly<PropsWithChildren<PreviewItemProps>>, nextProps: Readonly<PropsWithChildren<PreviewItemProps>>) {
const areEqual = prevProps.fileObject === nextProps.fileObject
console.log("Are equal?", areEqual)
return areEqual
})
我的问题是,即使 React.memo 的 propsAreEqual函数返回 true,组件重新渲染 - 如果父级重新渲染 - 在上传图像时,请求重新启动。
我想念 React.memo 的用法吗? ?

最佳答案

来自 docs :

React.memo only checks for prop changes. If your function componentwrapped in React.memo has a useState or useContext Hook in itsimplementation, it will still rerender when state or context change.


在内部,您应该检查您的 isLoading 状态:
useEffect(() => {
...
if(!fileObject.isUploaded && !isLoading) {
setIsLoading(true)
...
}
...
}, [fileObject, isLoading])

关于reactjs - 子组件在父组件重新渲染时重新渲染,即使 React.memo 返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64993321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com