簡體   English   中英

由反應鈎子更新的渲染列表值

[英]Render list value updated by react hook

有一個計數器應用程序應該在倒計時發生時呈現。

一次渲染應該是 10

第二個渲染應該是 10 9

第三個渲染應該是 10 9 8

等等 ...

使用反應鈎子,完成這個任務是一個挑戰,因為當存儲倒計時值的變量的值更新時,組件不會被重新渲染。

計時器用於每 1.5 秒更新一次倒計時的值。 console.log語句中,變量的值已更新,但不會重新呈現組件。

import React, { useState, useRef } from "react";

import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";

const ListCounter = props => {
  const [count, setCount] = useState([10]);
  const [timerId, setTimerId] = useState(null);
  const countRef = useRef(count);
  countRef.current = count;
  const timerIdRef = useRef(timerId);
  timerIdRef.current = timerId;

  function calculate() {
    initialize();
  }

  const initialize = () => {
    setTimerId(
      setInterval(() => {
        let temp = countRef.current;
        if (temp[temp.length - 1] === 6) {
          clearInterval(timerIdRef.current);
          console.log("STOP!");
        } else {
          setCount(count => {
            temp.push(temp[temp.length - 1] - 1);
            console.log("TEMP: ", temp);
            return temp;
          });
        }
      }, 1500)
    );
  };

  return (
    <div>
      <Grid container justify="center">
        <Grid item>
          {count.map((v1, i) => {
            return (
              <Typography key={i} variant="h1" component="h2" gutterBottom>
                {v1},
              </Typography>
            );
          })}

          <Button variant="contained" onClick={calculate}>
            Count down
          </Button>
        </Grid>
      </Grid>
    </div>
  );
};

export default ListCounter;

請找到完整代碼的 CodeSandbox 鏈接

歡迎任何建議。

編輯 nifty-frost-6hev3

感謝@JaredSmith 為我指明了正確的方向。

const initialize = () => {
    setTimerId(
      setInterval(() => {
        let temp = countRef.current.slice(); // <---------
        if (temp[temp.length - 1] === 6) {
          clearInterval(timerIdRef.current);
          console.log("STOP!");
        } else {
          setCount(count => {
            temp.push(temp[temp.length - 1] - 1);
            console.log("TEMP: ", temp);
            return temp;
          });
        }
      }, 1500)
    );
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM