一、理解
- state是組件對象最重要的屬性, 值是對象(可以包含多個key-value的組合)
- 組件被稱爲"狀態機", 通過更新組件的state來更新對應的頁面顯示(重新渲染組件)
二、 強烈注意
- 組件中render方法中的this爲組件實例對象
- 組件自定義的方法中this爲undefined,如何解決?
a) 強制綁定this: 通過函數對象的bind()
b) 箭頭函數
3. 狀態數據,不能直接修改或更新
三、內部原理
1. render調用次數:1+n次(1是初始化的那次 n是狀態更新的次數)
2. 類中的方法默認開啓了局部的嚴格模式,阻止 this指向window
四、案例
標準寫法:
<script type="text/babel"> //1.創建組件 class Weather extends React.Component{ //構造器調用幾次? ———— 1次 constructor(props){ console.log('constructor'); super(props) //初始化狀態 this.state = {isHot:false,wind:'微風'} //解決changeWeather中this指向問題 this.changeWeather = this.changeWeather.bind(this) } //render調用幾次? ———— 1+n次 1是初始化的那次 n是狀態更新的次數 render(){ console.log('render'); //讀取狀態 const {isHot,wind} = this.state return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> } //changeWeather調用幾次? ———— 點幾次調幾次 changeWeather(){ //changeWeather放在哪裏? ———— Weather的原型對象上,供實例使用 //由於changeWeather是作爲onClick的回調,所以不是通過實例調用的,是直接調用 //類中的方法默認開啓了局部的嚴格模式,所以changeWeather中的this爲undefined console.log('changeWeather'); //獲取原來的isHot值 const isHot = this.state.isHot //嚴重注意:狀態必須通過setState進行更新,且更新是一種合併,不是替換。 this.setState({isHot:!isHot}) console.log(this); //嚴重注意:狀態(state)不可直接更改,下面這行就是直接更改!!! //this.state.isHot = !isHot //這是錯誤的寫法 } } //2.渲染組件到頁面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
簡寫(推薦):
1 <script type="text/babel"> 2 //1.創建組件 3 class Weather extends React.Component{ 4 //初始化狀態 5 state = {isHot:false,wind:'微風'} 6 7 render(){ 8 const {isHot,wind} = this.state 9 return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> 10 } 11 12 //自定義方法————要用賦值語句的形式+箭頭函數 13 changeWeather = ()=>{ 14 const isHot = this.state.isHot 15 this.setState({isHot:!isHot}) 16 } 17 } 18 //2.渲染組件到頁面 19 ReactDOM.render(<Weather/>,document.getElementById('test')) 20 21 </script>