[Suggestion]: Code example for StopWatch in "Referencing Values with Refs"

未關閉
#7,303 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
55/100
Issue 類型
文件
描述清晰度
描述清楚
活躍度
停滯
技術堆疊
javascript, react
領域
documentation

研究方向

開啟 issue 中連結的 Referencing Values with Refs 頁面,並檢視 StopWatch 範例。將它對 now、startTime 和 secondsPassed 的處理方式與建議的 ref/state 拆分進行比較,然後在適當時更新範例。完成的標準是頁面中的程式碼清楚地展示哪些值會觸發重新渲染,以及哪些值儲存在 refs 中。

由索引模型根據 Issue 內容生成。

描述

type: documentation
Summary

In the code sample of StopWatch, the DOM's re-rendering only depends on secondsPassed. now and startTime are just used for calculation. If they are treated as state, then very change on them will cause the re-rendering. Am I right?

Page

https://react.dev/learn/referencing-values-with-refs

Details

My suggestion is:

  • define now and startTime as ref
  • define secondPassed as state
import { useState, useRef } from "react";

export default function Stopwatch() {
  const startTime = useRef(null);
  const now = useRef(null);
  const [secondPassed, setSecondPassed] = useState(0);
  const intervalRef = useRef(null);

  function handleStart() {
    startTime.current = Date.now();
    now.current = Date.now();

    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      now.current = Date.now();

      if (startTime != null && now != null) {
        setSecondPassed((now.current - startTime.current) / 1000);
      }
    }, 10);
  }

  function handleStop() {
    clearInterval(intervalRef.current);
  }

  return (
    <>
      <h1>Hi, Time passed: {secondPassed.toFixed(3)}</h1>
      <button onClick={handleStart}>Start</button>
      <button onClick={handleStop}>Stop</button>
    </>
  );
}
主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
16 小時 6 分鐘
30 天內合併 PR
7

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

reactjs/react.dev 的其他 Issue

查看 reactjs/react.dev 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。