React

State

jyeounjae 2023. 1. 8. 17:18

Propsは純粋関数なので、値を変更してはいけない。

しかし、Comp内部で値を変更し出力したい時はStateを使用する。

 

Class ComponentではState LifeCycleがあり、その中でStateを管理してきましたが

Functional Componentではhookが新しく出来てからはhookを利用してStateの管理することが可能になった。


Class Component      ⇨   Functional Component

componentDidMount   useEffect

componentWillUnmount  useEffect

this.setState                        const [date, setState] = useState(###);


(最近のこと、そのため、Reactの勉強し始め

たばかりの場合はFunctional Componentだけ覚えておいていいらしい!error handle以外には!!)

 

注意事項は、Stateを直接変更しちゃだめ!(例えば、state = { ####};のように)

Stateに変更が起こると、ReactはそのCompをre-renderingするが、直接変更するとReactはそれを感知出来なく

UIに最新のStateが出力されません!そのため、Stateを変更したい時はuseState()を利用すること!

また、Stateは非同期てきだ。そのため、関数をパラメータとしてのsetState()を利用する。

setState((state, props) => { }); // state : initial state, props : updateが動いた以後のstate