3
1

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】propsで関数を受け渡す時はアロー関数でラップする

3
Posted at

やらかしたので記録します。
アロー関数でラップしないと、描画時に該当の関数が実行されてしまうようです。

問題

任意のユニークキーを引数に受け取り、データベースから一致する行を削除するReactアプリを作成中でした。

table.jsx
export const DataRow = ({ record, onClickDelete }) => {
    // 実際は他に各カラムのデータがある
    return(
            <button onClick={onClickDelete(record.id)}>削除</button>
    );
};
App.jsx
const onClickDeleteRecord = (uniqueKey) => {
    const deleteRecord = async(key) => {
        // keyをデータベースから削除するコード
    };
    deleteRecord(uniqueKey);
    
    const newRecords = records.filter((rec) => rec === uniqueKey);
    setRecords(newRecords);
    setError("");
}

このコードを描画した所、一覧に何も表示されなくなってしまいました。
該当のコードを編集前に戻しても何も表示されず。
もしやと思ってDBを見てみたら、データがすべて消えていました。

スクリーンショット 2024-08-05 223759.png

原因

propsの渡し方が間違っていました。
onClick={onClickDelete(record.id)}という渡し方をすると、描画時に実行されてしまうようです。

解決

アロー関数でラップすると、クリック時に呼び出されます。

table.jsx
export const DataRow = ({ record, onClickDelete }) => {
    return(
            <button onClick={() => onClickDelete(record.id) }>削除</button>
    );
};

最後に

DBデータが飛んだのは焦りました、気を付けようと思います。
ほぼ作りたての環境で良かったです。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?