0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React完全ガイド ~問題への対処法~

Posted at

参考教材

問題への対処法

エラーの解消方法

赤波線

2025-10-10 21.18の画像.jpeg

文法の書き方ミス

// 修正
return (
    <>
      <p>現在のカウント数: {count}</p>
      <button onClick={countUp}>+</button>
    </>

  );

定義されていない

2025-10-10 21.27の画像.jpeg

2025-10-10 21.26の画像.jpeg

// 修正
import { useState  } from "react";

const Example = () => {
  const [count, setCount] = useState({ val: 0 });

エラーはないけど動かない

コードのデバック

コードを止めてその状態の変数の中身や、渡されている値が正しいかを確認する作業

2025-10-10 21.38の画像.jpeg


①ボタンは問題なく動いているか?

<button onClick={countUp}>+</button>

const countUp = () => {
    console.log('ボタンが押されました');
};

2025-10-10 21.47の画像.jpeg


②ボタンの機能も正常に動いているか?

const countUp = () => {

  setCount((prevstate) => {
  console.log('コールバックON');

  // valの初期値は0 +1
  prevstate.val += 1;
  console.log(prevstate);
      
  return prevstate;
  });
};

2025-10-10 21.54の画像.jpeg


③再レンダリングされているか?

const Example = () => {
  const [count, setCount] = useState({ val: 0 });

  console.log('再レンダリングしてる?');
};

2025-10-10 21.59の画像.jpeg

この結果から分かるのは、中のオブジェクトの結果は変わっているが画面が変わっていないので、再レンダリングされていないのが分かる。


修正する

エラーや不具合の原因をgoogleやAIに聞いて修正する

// 修正
const countUp = () => {

  setCount((prevstate) => {

    // objが渡ってきたら、新しいobjにコピーしてreturnする
    const newState = { ...prevstate }
    
    newState.val += 1;
    return newState;
    });
  };

2025-10-10 22.06の画像.jpeg

デバッカーを使ってみよう

デバックとはコードを1行1行確認しながら実行すること
デバッカーを使うことで、その部分でデバックを一時停止できる

現在の問題点を見つける

2025-10-10 22.18の画像.jpeg

①現在のカウント数の数字が出ない

const Child = (countNum) => {
  
  // 確認したい箇所の上でdebuggerを置く
  debugger

  // 本来数字が表示される箇所を見つける
  return <p>現在のカウント数: {countNum.val}</p>
}

2025-10-10 22.27の画像.jpeg

2025-10-10 22.31の画像.jpeg

{countNum.val} が undefined と出ている
これは、Childコンポーネントの関数が実行中の countNum.val の値が undefined となっているので、画面上に表示されなかった


countNumをコンソールで確認しよう

2025-10-10 22.36の画像.jpeg

// ①propsの分割代入は({})で囲わないといけない
// ②数字を受け取っているのはcountNumではなくcountである
const Child = ({count}) => {
  debugger
  return <p>現在のカウント数: {count.val}</p>
}

2025-10-10 22.40の画像.jpeg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?