React+ANTD項目使用後的一些關於生命周期比較實用的心得
阿新 • • 發佈:2018-05-09
react clas 增加 服務 容易出錯 渲染 return xxx stat
1. constructor()
constructor(props){ super(props) this.state=({ }) }
一定先寫super 可以接收從父組件傳來的值
父組件往子組件傳值的方法
<ChildComponent nextValue={xxx.xxx} nextValue2={xxx.xxx}/>
直接在組件中寫屬性名等於屬性值就可以,有多少傳多少
在子組件 ChildComponent 中獲取父組件傳來的值只需要用
this.props.nextValue
就可以得到父組件傳來的值
由此衍生一個問題,子組件如何給父組件傳值
首先,需要在父組件定義一個方法(agechange),然後將方法傳給子組件,
class App extends Component { agechange=(age)=>{ alert(age) } render() { return ( <div className="App"> <Child agechange={this.agechange}/> //將方法傳給子組件 </div> ) } }
在子組件中調用這個方法,將需要傳給父組件的值,通過這個方法傳給父組件,
class Child extends Component { constructor(props){ super(props) this.state=({ age:0 }) } handleChange=()=>{ this.setState({ age:this.state.age+3 }) this.props.agechange(this.state.age) //將子組件的age值傳給父組件 } render(){return( <div> <button onClick={this.handleChange.bind(this)}>點擊增加age</button> </div> ) } }
2.componentWillMount
關於componentWillMount方法只想說一點,它的調用在constructor之後,在render之前,在這方法裏的代碼調用setState方法不會觸發重渲染
3.componentDidMount
一般的從後臺(服務器)獲取的數據,都會與組件上要用的數據加載有關,所以都在componentDidMount方法裏面作
4.componentWillReceiveProps
當父組件傳給子組件的props發生改變時,子組件可以通過componentWillReceiveProps 方法接收,可以setState 重新渲染組件
當父組件通過ajax異步獲取的值需要傳給子組件時,子組件可以用到componentWillReceiveProps(nextProps)
關於setState() 它不是同步的,也不能說是異步的,所以不要在setState之後,直接用state中的值,很容易出錯。
React+ANTD項目使用後的一些關於生命周期比較實用的心得