简体   繁体   English

如果在回调 function 中调用 useState 不会重新渲染组件

[英]useState not re-rendering component if it is called inside callback function

I have a component to upload a video and I am trying to show the progress bar.我有一个上传视频的组件,我正在尝试显示进度条。 Here is my core code.这是我的核心代码。

const Upload = () => {
  const [percent, setPercent] = useState(0);
  console.log(percent); // This logs uploaded percentage every time progListener callback is called. From 0 to 100.
  const dropAccepted = async () => {
    const params = {...} // parameters to upload video like filename, file
    await APIs.uploadVideo(params, progListener);
  }
  const progListener = (event) => {
    var p = Math.round((event.loaded * 100) / event.total)
    // console.log(p) logs uploaded percentage from 0 to 100
    setPercent(p);
  }

  return (
    <h6>{percent}</h6>  
    <Dropzone onDropAccepted={dropAccepted}/>
  )
}

On progListener callback, I have updated the percent with setPercent function so I think h6 should print uploaded percentage.在 progListener 回调中,我用setPercent function 更新了百分比,所以我认为h6应该打印上传的百分比。 But it always 0. What's wrong on my code?但它总是 0。我的代码有什么问题? I would appreciate any help.我将不胜感激任何帮助。

Update it with useRef,用 useRef 更新它,

The reason why useState doesnt show the latest value is because useState is asynchronous. useState 不显示最新值的原因是因为 useState 是异步的。 So in your case useState is being updated without giving it a chance to re-render.因此,在您的情况下, useState 正在更新,但没有给它重新渲染的机会。 In these cases useRef plays a better role.在这些情况下,useRef 发挥了更好的作用。

import React, {useRef} from "react";

const Upload = () => {
  const percent = useRef(0);

  const progListener = (event) => {
      percent.current = Math.round((event.loaded * 100) / event.total)
  }

  return (
    <h6>{percent.current}</h6>  
    <Dropzone onDropAccepted={dropAccepted}/>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM