反应如何进行重新渲染以更新本地存储中的值

时间:2020-07-14 06:11:40

标签: javascript reactjs material-ui

当我的react应用程序中有文件上传时,我试图显示一个带有百分比值的微调器。我正在使用实体UI circular progress来做到这一点。因此,我将使用Axios打个电话,并将其配置为提供百分比值并将其保存到本地存储中。我的休息电话的代码如下:

callRestService(URL,postBody){
 const config = {
    onUploadProgress: function(progressEvent) {
    var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
    console.log(percentCompleted);
    localStorage.setValue('percentage',''+percentCompleted);
   }
 }
 axios.post(URL, postBody, config)
    .then(res => console.log(res))
    .catch(err => console.log(err))
}

微调器组件的代码段为

export default function CircularProgressWithLabel(props) {
  const initialPercentage = () => Number(localStorage.getItem('percentage') || 0);
  const [percent,setPercent] = React.useState(initialPercentage);
  React.useEffect(() => {
    setPercent(Number(localStorage.getItem('percentage')));
  },[localStorage.getItem('percentage')])
  return (
    <Box position="relative" display="inline-flex">
      <CircularProgress variant="static" {...props} />
      <Box
        top={0}
        left={0}
        bottom={0}
        right={0}
        position="absolute"
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <Typography variant="caption" component="div" color="textSecondary">
          {percent}
        </Typography>
      </Box>
    </Box>
  );
}

我通过这种方式在父组件中使用了这两个辅助方法:

function mainComponent(){
  ...
  const [loading,setLoading] = React.useState(false);
  ...
  // this function will be called when a button is clicked.
  async function importFile(){
    setLoading(true);
    await callRestService('endpontURl',data);
    setLoading(false);
  }

  ...

  return{
    ...

    { loading && <CircularSpinner/> }
  }
}

现在的问题是微调器组件仅渲染一次,即每当我将loading钩子设置为true时,由于圆形微调器中百分比的初始值为零,因此不会显示微调器组件。但是后来我更新了callRestService中的localStorage值,并具有一个useEffect来监听Spinner组件中的localStorage值,我希望每次在callRestService中更新值时都将呈现Spinner组件,但这没有发生。因此有人可以帮我解决这个问题,我想在本地存储值每次更新时渲染微调器组件,从而提供一种获取最新上传百分比值的方法。还是可以选择将Axios在callRestService组件中返回的值提供给Spinner组件。

1 个答案:

答案 0 :(得分:2)

通常使用状态更改来呈现组件,您可以将一个状态绑定到本地存储(如果仍然需要本地存储),并且每次只更新状态