React props or state
分割その二
props
super(props); this.message = 'Hello from Note Component'; this.noteContent = props.noteContent; this.noteId = props.noteId;
propsのdataをclass直下に渡すことができる,??
State
constructor(props) { super(props); this.state = { notes: [ {id:1, noteContent: "Note 1 here"}, {id:2, noteContent: "Note 2 here"}, ], } }
propsとしてthisに直接書く以外に,stateとしてclassのconstructor で定義し,setStateで更新,追加することができる
props
アロー関数でもpropsは気軽に書ける。
const post = (props) => { return ( <div> <h1>{props.title}</h1> </div> )
しかしこれにはstateは入らない。
stateを宣言or使用するためにはclassを書く必要がある。
stateは変化した時に全体が再描画されるが, propsはされない。(ではなんのためにComponentWillMountがあるんだ?)
addNote(note) { this.state.notes.push(note) }
そしてComponentWillMountで更新する方法があるが,それは現在は 非推奨なので,
hooks, useState, useEffectで更新することが推奨されている