🛠️ 今日触った技術
- Array.from() (動的配列生成)
- Zustand (状態管理とデバッグ)
🎯 やりたかったこと
ユーザーが入力した問題集の「章数」に応じて、その数だけ入力コンポーネントを動的に生成したかった。
章数: 3 を入力
↓
第1章の節数: [入力欄]
第2章の節数: [入力欄]
第3章の節数: [入力欄]
💡 Array.fromの理解が深まった
最初は「Array.fromって何?」状態だったんですが、実際に使ってみて理解できました。
Array.fromの基本動作
// 基本形: 指定した長さの配列を作成
Array.from({ length: 3 })
// 結果: [undefined, undefined, undefined]
// 応用形: 作成と同時に各要素を変換
Array.from({ length: 3 }, (_, index) => `第${index + 1}章`)
// 結果: ["第1章", "第2章", "第3章"]
React でのコンポーネント生成
const chapterCount = 3; // ユーザー入力値
{Array.from({ length: chapterCount }, (_, index) => (
<SectionCountInput
key={index} // React用の一意キー
chapterNumber={index + 1} // 表示用(1, 2, 3...)
chapterIndex={index} // データ操作用(0, 1, 2...)
/>
))}
これで章数分だけコンポーネントが自動生成される!
他の書き方との比較
// 方法1: Array.from(今回採用)
Array.from({ length: 3 }, (_, index) => <Component key={index} />)
// 方法2: スプレッド構文 + map
[...Array(3)].map((_, index) => <Component key={index} />)
// 方法3: for文(あまり使わない)
const components = [];
for (let i = 0; i < 3; i++) {
components.push(<Component key={i} />);
}
Array.fromが一番読みやすくて分かりやすいですね。
🚧 本日のエラー発生ポイント
1. React Hooksの使用場所
最初、こんなコードを書いてエラーになりました:
// ❌ コンポーネント外でhooks使用
const chapterCount = useQuizBookStore(state => state.currentQuizBook?.chapterCount || 0);
const AddQuizBook = () => {
return (
<Text>現在の状態: {chapterCount}</Text>
);
}
問題: コンポーネント外でhooksを使用すると、状態が更新されても再レンダリングされない。
// ✅ 正しい書き方
const AddQuizBook = () => {
const chapterCount = useQuizBookStore(state => state.currentQuizBook?.chapterCount || 0);
return (
<Text>現在の状態: {chapterCount}</Text>
);
}
2. デバッグの重要性
Array.fromが動かない原因を特定するのに、段階的なデバッグが効果的でした:
// Step 1: データの確認
console.log('chapterCount:', chapterCount);
// Step 2: method の実行確認
console.log('Array.from結果:', Array.from({ length: chapterCount }));
// Step 3: コンポーネント生成の確認
{Array.from({ length: chapterCount }, (_, index) => {
console.log('コンポーネント生成中:', index);
return <SectionCountInput key={index} />;
})}