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?

More than 1 year has passed since last update.

【React】「RuntimeError:array.includes is not a function」の解決法

Last updated at Posted at 2023-12-05

エラー内容

React公式チュートリアルの問題4を解いていたところ、以下のエラーが出ました。

App.js: selectedIds.includes is not a function

原因

includes()は、指定した配列に特定の要素が含まれているかどうかを真偽値で返すメソッドです。

このエラーは配列以外のものを指定したせいで発生しています。

具体的に言うとselectedIdsが配列ではないということになります。

しかし、useStateの定義を見るとちゃんと配列で初期化できています。

const [selectedIds, setSelectedIds] = useState([]);

ということは、途中で誤って配列以外に更新しているということになります。

❌ 誤

setSelectedIds()を確認すると、誤りがありました。。
これだと値を1 2 3 4のようにバラバラに渡していることになります。

setSelectedIds(...selectedIds,toggledId);

⭕️ 正

配列にして渡します。

setSelectedIds([...selectedIds,toggledId]);

おわりに

関数の引数として配列を渡すとき、すでに()があるせいか[]を忘れがち。。

おまけ:数値に対してincludesを使いたい場合

今回の事例では無関係ですし、完全にJavaScriptの話ですが、数値をincludesに渡すこともできないので、文字列に変換して渡しましょう。

❌ 誤

const number = 123;

console.log(number.includes(2));

⭕️ 正

const number = 123;

console.log(number.toString().includes(2)); // true

参考

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?