如何定義state 在類組件 中,在constructor()中使用this.state={}來定義 class A extends Component { constructor (props) { super(props) // 調用Component的構造函數 // 定義state this. ...
如何定義state
在類組件 中,在constructor()中使用this.state={}來定義
class A extends Component { constructor (props) { super(props) // 調用Component的構造函數 // 定義state this.state = { num: 1 } } }
在函數組件中,自React(16.8)版本以後,使用useState()來定義。
function B (props) { // 定義state聲明式變數 let [num, setNum] = useState(1) }
如何使用state
- 在類組件中,使用this.state訪問聲明式變數。
- 在函數組件中,直接訪問useState的結果。
如何修改state聲明式變數
在類組件中,使用this.setState()方法來修改。
class A extends Component { constructor (props) { super(props) // 調用Component的構造函數 // 定義state this.state = { num: 1 } } this.setState(state=>({num: state.num + 1}), ()=> {console.log( this.state.num)}) } }
在函數組件中,使用useState()返回值的第二個參數(set*)方法來修改。
function B (props) { // 定義state聲明式變數 let [num, setNum] = useState(1) const add = () => { console.log('1--- num', num) // 如果這裡是React(V17)中,在合成事件中是非同步的,如果在巨集任務或 Promise.then()是同步的。 // 如果這裡是React(18),無論在哪裡都是非同步的。 // useState()給的這種set*方法,是沒有callback的。 // setNum(num + 1) setNum(num => num + 10) console.log('2--- num', num) } }
this.setStaate()的兩種寫法
- this.setState({},callback)當我們修改state時,如果舊值與新值無關,建議使用這種寫法。
- this.setState((state)=>{},callback)當我們修改state時,如果舊值與新值有關,建議使用這種寫法。
this.setState()的非同步性
-
在React(v17/v16)中,this.setState()在合成事件(事件,生命周期中)是非同步的;在巨集任務、promise.then()中是同步的。
-
在React(v18)中,無論this.setState()在哪裡都是非同步的,這種特性,被稱之為“併發模式”。
-
this.setState()定為非同步是為了性能優化。
this.setState()自動合併
在同一個函數域中,多個this.setState()會自動合併,以減少沒必要的diff運算(協調運算);自動合併的規則是一種淺合併。