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で使うStateに関する基礎知識

Last updated at Posted at 2021-03-18

はじめに

私が学んだstateについてのアウトプットです。

自分自身の健忘録であり、誰かの役に立てれば尚嬉しいです。

stateとは?

stateとは状態のことであり、可変のデータである。
stateが変更されると、仮想DOMとの差分をとり、実際のDOMを更新し、コンポーネントを再描画します。

またstateではlocal stateとglobal stateの2つに分けられます。

  1. コンポーネントの中で管理する変数(local state)
  2. Reduxを使うことでどのコンポーネントからも参照できる(global state)

なぜstateを使うのか?

render()内では無限に再レンダーされてしまうことを防ぐため、値を変更してはいけないというルールがあります。
そのため、render()内で値を変更するためには**setState()**を使って値を変更する必要があります。
そうすることで、ページリロードせずにコンポーネントを再描画し、表示を切り替えることができます。

どうやって使うのか?

まず、stateは基本的にfunctional componentでは使用できません。
そのため、class component内で、かつconstructor内で使用する必要があります。
(React Hooksを使えばfunctional componentでも使用できます)
記述方法はObject型です
書き方の例↓


class Qiita extends React.Component {
  constructor(props) {
    super(props);
      this.state = {
      isPublished: false
     }
  }
  //中略
}
export default Qiita;

参考

https://ja.reactjs.org/docs/state-and-lifecycle.html
https://qiita.com/kyrieleison/items/78b3295ff3f37969ab50
https://www.youtube.com/watch?v=j4t0aZge0Mc&t=194s

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?