DoubleTian-tw / pokemon-Gym

https://pokemon-gym.vercel.app/
9 stars 1 forks source link

避免在 component 內定義 component #10

Closed QzCurious closed 7 months ago

QzCurious commented 7 months ago

通常不建議在 component 裡面定義 component,因為如此一來每次 re-render 的時候內層的 component 都會是新的 function,造成內層 component 的狀態被重新初始化,也就會阻斷使用 React.memo 跳過 render 的機會。

狀態被重新初始化的範例

https://github.com/DoubleTian-tw/pokemon-Gym/assets/38932402/97fa40ce-9ddd-4b5d-bacb-5e04b1772bb9

function RootComp() {
  const [count, setCount] = useState(0);
  function ChildComp() {
    return (
      <div>
        <div>Name: </div>
        <StatefulComp />
      </div>
    );
  }

  return (
    <div className="p-4">
      <div>count: {count}</div>
      <button className="btn btn-light" onClick={() => setCount(count + 1)}>
        count++
      </button>
      <ChildComp />
    </div>
  );
}

function StatefulComp() {
  const [name, setName] = useState("Hi");
  return (
    <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
  );
}

任務

這會是個好習慣

另外,養成這個習慣後寫的程式碼也會自然地拆得比較乾淨,後面我慢慢提到 stateful comopnent, pure component 時就會 recall 回這裡了

DoubleTian-tw commented 7 months ago

eeb3232 將CheckBestDamage component從parent component移出

QzCurious commented 7 months ago

我給的錄影看有沒有問題再跟我說一下

DoubleTian-tw commented 7 months ago

沒U問題喔

QzCurious commented 6 months ago

React 官方文件也提到不要在 component 內定義 component: Nesting and organizing components