LoginSignup
2
0

More than 3 years have passed since last update.

React jsx 迷ったことまとめ

Last updated at Posted at 2020-06-28

常時追加していくやつ。
React始めたばかりの初心者のため間違えていたらご指摘よろしくおねがいします。

Inputにて数字の入力のみを許すようにする

onInput={(e) => { e.target.value = e.target.value.replace(/[^0-9]/g, ''); }}

をInputタグに追加する。

<input
    type="text"
    className="form-control form-control-sm"
    name="なまえ"
    value={''}
    onChange={handleOnChange}
    onInput={(e) => { e.target.value = e.target.value.replace(/[^0-9]/g, ''); }}   // <-これ
/>

配列(Array)を重複削除する方法

これはSetつかうんだよー!

const array1 = [1, 5, 3, 1, 5, 3];
const array2 = Array.from(new Set(array1))
console.log(array2); // [ 1, 5, 3 ]

引用元:
JavaScriptで重複排除を自分で実装してはいけない(Setを使う)

連想配列(オブジェクト)を重複削除する方法

こっちは上述のSetつかう方法ではできないよね? ...よね? IndexOfつかっちゃうよ? 怒る?:sweat:

const jyuhukuArray = [
    { name: "スズキ" ,hoge: 'hoge' },
    { name: "キムラ" ,hoge: 'hoge' },
    { name: "スズキ" ,hoge: 'hoge' },  //重複
    { name: "サトウ" ,hoge: 'hoge' },
    { name: "サトウ" ,hoge: 'hoge' },  //重複

];
let values = [];
let noJyuhukuArray = jyuhukuArray.filter(e => {
  if (values.indexOf(e["name"]) === -1) {
    values.push(e["name"]);
    return e;
  }
});
console.log(noJyuhukuArray)

「...」ってなんじゃいこら:rage:

スプレッド構文っていうんだよ。説明見ようず

他のRouteにState渡したいんだが

渡せる。
既存の申請をコピーして、新しい申請を作成する、みたいな機能で使う。

呼び出し元.jsx
const { history } = this.props;
const originalForm = {
    name: "コピー元の申請書",
}
history.push({
    pathname: '/application/new', //ページ遷移先
    state: {
        form: originalForm,
    },
});

呼び出し先.jsx
const { location } = this.props;
if (location.state) {  // コピー元から遷移してない場合location.stateはUdefinedになる 
    const newForm = location.state.form,
}

これでOK

Use array destructuring prefer-destructuring でeslintちゃんに怒られる

ぼーっと生きてた、、、

let object = {};
if (e.list.length === 1) {
  object = e.list[0];  //prefer-destructuring!! ぼーっと生きてんじゃねえよ!!!!!!!
}
let object = {};
if (e.list.length === 1) {
  [object] = e.list;  // OK!! つまんねーやつだなー
}
2
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
2
0