ReactJS入門 - ClassComponent 中使用 state
state 是什麼
在前幾個篇章當中我們提到了只有當 Props 以及 State 的值被更新了, React 才會使畫面重新渲染。而 State 是 ClassComponent 中一種特別的成員變數,當值被改變時即會觸發 re-render 的過程。
在 functionalComponent 當中,ReactHook 也有提供 useState 這個 Hook,對應提供本篇要介紹 state 的功能,我們會在後面的篇章再提及。
宣告與初始值
state 是一個物件,在建構子當中宣告:
this.state={ 變數名稱A: 初始化值, 變數名稱B: 初始化值, //... };
例如
constructor(props){
super(props);
this.state = {
percent : 30,
helloMsg : "hola~"
};
}
在這裡宣告了一個名為 percent 以及 helloMsg的 state,並設定初始值。
讀取
讀取方式與 props 相同
this.state.變數名稱
例如我們用一個 <h1> 來取出 percent 的值
import React from 'react';
import { Component } from 'react';
class App extends Component{
constructor(props){
super(props);
this.state = {
percent : 30,
helloMsg : "hola~"
};
}
render(){
return(
<div>
<h1> { this.state.percent } </h1>
</div>
);
}
}
export default App;
執行之後你就會看到大大的 30 印在畫面上
修改
state 與 props 一樣是唯讀的,必續透過內建方法 this.setState 去修改。而 setState 中也要傳入一個物件,就像是上面宣告 state 一樣。
this.setState({ 變數名稱:修改值 })
例如寫一個 plusPercent 方法來修改 state 的值,每呼叫一次函式就會把 percent 加一
plusPercent(){ this.setState({ percent:this.state.percent + 1 }) }
然後記得去建構子綁定函式
constructor(props){
super(props);
this.state = {
percent : 30,
helloMsg : "hola~"
};
this.plusPercent = this.plusPercent.bind(this);
}
然後把函式綁到按鈕上面
render(){
return(
<div>
<h1> { this.state.percent } </h1>
<button onClick={ this.plusPercent }>++</button>
</div>
);
之後點擊 ++ 就可以看到數字增加
移除
如果要移除某個 state,將其宣告為 undefined 即可:
this.setState({helloMsg: undefined});
setState 的規則
1. 在建構子已被宣告的值,而在 setState 中沒被寫到,不會被移除
例如我們剛剛宣告了兩個 state
this.state = { percent : 30, helloMsg : "hola~" };
而在 setState 的時候只更新了 percent,但是 helloMsg 並不會被移除。
2. 在建構子沒被宣告的值,但在 setState 中被寫道則會被建立
如同上面目前有 percent 以及 helloMsg 兩個 state,如果 setState 這樣寫的時候:
this.setState({ name: "hazuya" })
這樣 name 這個 state 就會被建立,也就是說不一定要透過建構子宣告 state,可以透過 setState 宣告。
3. 利用變數設定 state,可以只寫變數名稱
etState 會去尋找有沒有與目前 state 同名稱的成員變數,如果有就更新 state 的值;如果同名的 state 不存在則會建立一個同名的 state,例如:
let name = "ted" this.setState({name})
如果有 name 這個 state,值就會被更新為 ted,如果 state 不存在,就會建立一個名為 name 的 state 且值為 ted。
4. 如果 state 宣告的是物件,不能修改單一屬性
例如宣告一個 selfStyle 的 state:
this.state = { selfStyle : { color:"blue", background: "white" } };
在使用 setState 更新 selfStyle 的時候如果這樣寫:
this.setState({selfStyle:{color:"black"}});
background 就不會被保留,如果要保留可以這樣做:
this.setState({ selfStyle:{ color: "black", background: this.state.selfStyle.background } });
就是將原本 background 屬性傳給自己
5. setState 不會馬上做完
JavaScript 異步的關係,有時候 setState 還沒執行完成就會執行到下面的程式碼,例如更新後要印出新的值,如果需要等 setState 完成之後才做某件事情,可以使用 setState 的第二參數:
this.setState({percent: 70},()=>{ console.log(this.state.percent); } )
這樣就一定會印出 70 ,如果沒有這樣寫有可能會拿到舊的 state 值。
結論
本篇介紹了在 classComponent 中使用 state 的方式,已經基本上可以掌握畫面的更新了!同樣的 ReactHook 也提供了這樣的功能,我們會在之後的篇章介紹到。
下一篇將會介紹元件的生命週期函數,主要可以在元件被安裝、元件被更新、元件被移除三種階段,而利用這些函數可以決定每個階段要做什麼事情。
Originally published at https://studio-44s.tw.