在页面刷新时,进度值变为 0 并移动到下一页 React Redux

On page refresh the progress value becomes 0 and moves to the next page React Redux

我想在MongoDB中保存进度,然后显示进度。正在计算和更新进度值。但是当我刷新页面时,进度值变为 0 并且在两者之间移动到下一页。

const Quiz = (props) => {
   const {progress: lastProgress, userId} = props; 
    const [progress, setProgress] = useState(lastProgress || 0);
    const dispatch = useDispatch();
    const history = useHistory();
  
    const classes = useStyles();
    

useEffect(() => {
    
          async function fetchProgress(){
            try{
          const progress = await api.get(paths.FETCH_USER);
          const newprogress = progress.progress;
          console.log(newprogress + "alpha");
          if (newprogress <= 100) {
            setProgress(Number(newprogress));
          }}
        catch(error){
          console.log(error);
        }
        };
          fetchProgress();
        }, []);
      
      
        useEffect(() => {
          async function updateProgress() {
            try {
              await api.patch(paths.UPDATE_USER, JSON.stringify({progress}))
                console.log(progress + "valueof");
            }
            catch(error){
              console.log("error", error);
            }
          };
          updateProgress();
        }, [progress]);
      
       function handleSubmit(event) {
            event.preventDefault();
             
            const valid = questions.some((q) => !q.value);
            console.log(valid + "questionsalpha");
            if (!valid) {
                dispatch(postAssessment({ responses: questions, id: assessment.id }, history));
            }
            setCurrentQuestion(0);
           setChecked((previousState) => !previousState);
           setTimeout(() => { 
            setChecked(previousState => ({
                 afterPreviousChange: previousState.previousChange
               }))
          }, 1000);
          setProgress((prevProgress)=> prevProgress + 10);  
        
        }
        return (
       <Grid item md={4} >
                <Fragment>
                  <Grid item xs={12} md={6} sm={6}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Box sx={{ width: '100%', mr: 1 }}>
                    <LinearProgress variant="determinate" orientation="vertical" value={progress} />
                    </Box>
                    </Box>
                  </Grid>
                </Fragment>
    
              </Grid>
              )
    );

我能够计算进度值并存储该值,但在页面刷新时进度值变为 0。不知道我犯了什么错误。 任何帮助将不胜感激。

我认为您只需要将 progress 状态持久保存到长期存储中,以便在重新加载页面后可以访问它。使用 localStorage 在更新时保持 progress 状态。延迟从 localStorage 初始化 progress 状态。这避免了任何通过 PATCH 请求意外地将进度“重置”回 0 的问题。

示例:

const Quiz = (props) => {
  ... 
  const [progress, setProgress] = useState(() => {
    return Number(JSON.parse(localStorage.getItem("progress")) ?? 0);
  });

  ...
    
  useEffect(() => {
    async function fetchProgress() {
      try {
        const { progress } = await api.get(paths.FETCH_USER);
        console.log(progress + "alpha");
        if (progress <= 100) {
          setProgress(Number(progress));
        }
      } catch(error) {
        console.log(error);
      }
    };

    fetchProgress();
  }, []);
      
  useEffect(() => {
    async function updateProgress() {
      try {
        await api.patch(paths.UPDATE_USER, JSON.stringify({ progress }))
        console.log(progress + "valueof");
      } catch(error){
        console.log("error", error);
      }
    };

    updateProgress();
    localStorage.setItem("progress", JSON.stringify(progress));
  }, [progress]);
      
  function handleSubmit(event) {
    event.preventDefault();
    ...
    setProgress((progress) => progress + 10);  
  }

  ...
);