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 3 years have passed since last update.

React Hooks メモ

Posted at

React Hooksとは

  • ver16.8から導入。
  • stateをクラスで書かなくてもfunctionベースで利用できるようになる。

useState

//install
import React, { useState } from "react";

const App = () => {
   //useStateは配列を返す。
  const [count, setCount] = useState(0) //初期化
  //そして、2つの要素を返す。(2) [初期化した値:0, 値を操作する関数:ƒ]
  console.log(typeof count) // number
  console.log(typeof setCount) // function

  return (
    <div>
      <h1>First Display</h1>
    </div>
  );
}

export default App;

case setCountを使用してカウントを変化させる。


import React, { useState } from "react";

const App = () => {

  const [count, setCount] = useState(0)
  //setCountの引数にcountを渡してインクリメントする。
  const increment = () => {setCount(count + 1)}
  const decrement = () => {setCount(count - 1)}

  //setCountの引数に変化させる前の状態を渡し、その値をインクリメントすることができる。
  const increment2 = () => {setCount((preve) => preve + 1)}
  const decrement2 = () => {setCount((preve) => preve - 1)}

  const reset = () => {setCount(0)}
  const double = () => {setCount((preve) => preve * 2)}

  const d = () => {
    setCount((preve) => {
    if (preve % 3 === 0) {
      return preve / 3
    } else {
      return preve
    }
    }
  )}

  return (
    <>
    <div>
    <h3>count1: {count}</h3>
      {/* onClickイベントでsetCountを発火させる */}
      <button onClick={increment}>+1</button>
      <button onClick={decrement}>-1</button>
    </div>
    <div>
    <h3>count2: {count}</h3>
      <button onClick={increment2}>+1</button>
      <button onClick={decrement2}>-1</button>
      <button onClick={reset}>Reset</button>
      <button onClick={double}>double</button>
      <button onClick={d}>d</button>
    </div>
    </>
  );
}

export default App;

case 複数の状態を管理する。

import React, { useState } from "react";

const App = () => {

  //コンストラクタを用意
  const initialStates = {
    name: '',
    price: 1000
  }
  //それぞれのuseStateを設定する。
  const [name, setName] = useState(initialStates.name)
  const [price, setPrice] = useState(initialStates.price)

  const reset = () => {
    setPrice(initialStates.price)
    setName(initialStates.name)
  }

  return (
    <>
    <p>現在:{name}{price}円です。</p>
    <button onClick={() => setPrice((prive) => prive + 1)}>+ 1</button>
    <button onClick={() => setPrice((prive) => prive - 1)}>- 1</button>
    <button onClick={reset}>reset</button>
    <input type="text" value={name} onChange={event => setName(event.target.value)}/>
    </>
  )
}

export default App;

case オブジェクトを渡す。

  1. useStateにオブジェクトそのものを渡すこともできる。

  //別々に渡していた場合。
  const initialStates = {
    name: '',
    price: 1000
  }

 const [name, setName] = useState(initialStates.name)
 const [price, setPrice] = useState(initialStates.price)

 //オブジェクトそのものを渡す場合
 const [state, setState] = useState(initialStates) 

 //こちらの方がスッキリする。

 //stateにはオブジェクトが入っているため、...stateとして分割する必要がある。
  <button onClick={() => setState({...state, price: state.price + 100})}>+ 100</button>
  <input type="text" value={state.name} onChange={e => setState({...state, name: e.target.value })} />

useEffect

  • インストール
  • import React, { useState, useEffect } from "react";

ライフサイクルフックのmouthedのようなもの。

  • レンダリングの後にマウントされる。
  • イベント毎に発火する。

//console.logで呼び出される順番を確認できる。
import React, { useState, useEffect } from "react";


 
const App = (props) => {

  const [state, setState] = useState(props)


  //第一引数:関数
  //第二引数:最初のレンダリングのみ発火する場合は[]を付与。
  //任意のstateのイベントのタイミングときに発火する場合は[name]などのstate名を付与する。
  useEffect(() => {
    console.log('useEffect is invoked.')
  }, [])

  const renderPeriod = () => {
    console.log('renderPeriod renders period.')
    return ''
  }

  return (
    <>
    <p>{renderPeriod()}</p>
    <div>
      <label>銘柄の変更</label>
      <input value={state.name} onChange={e => setState({...state, name: e.target.value})} />
      <p>銘柄{state.name}の1株の値段は{state.price}円です。</p>
      <button onClick={() => setState({...state, price: state.price + 100})}>+ 100 called</button>

    </div>
    </>
  )
}

App.defaultProps = {
  name: '',
  price: 1000
}



export default App;

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?