將函數組件轉換為函數組件
- 創建一個同名的類組件并且繼承React.Compoent
- 添加一個空的方法叫做render()
- 把函數里面的內容移到render方法里面
- 把render()里面的props替換成this.props
- 刪掉之前的函數聲明的組件
//最后執行第5步,刪掉函數聲明的組件,這里作為演示,所有不做刪除
function Welcome(props){
return <h1>Hello {1 + props.num}</h1>
}
class Welcome extends React.Component {
render(){
<h1>Hello {1 + this.props.num}</h1>
}
}
state狀態
在官網的例子中,當前學到更新UI的方式是重新創建一個element,并render到頁面中。在這里將使用state來實現UI更新。
state和props很相似,但state是屬于組件私有的屬性,并且可以改變的
添加state
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
生命周期
componentDidMount 組件掛載后執行(渲染到dom節點)
componentWillUnmount 組件卸載后執行
正確使用state
- 官方建議修改state使用 setState方法 this.setState({comment: 'Hello'});
- 唯一聲明state僅限在contructor中進行
更新state
更新state是一個異步的過程,如果依賴他們的值來計算下一個state,則可能會出現錯誤
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
為了解決這個問題,讓setState()接收一個函數比接收一個對象的方式更好。
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
等價于
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
};
});
單向數據流
在react中無論父組件還是子組件都無法知道其他組件的狀態,子組件可以接受父組件傳遞的數據,父組件可以通過狀態選擇子組件,這樣的自上而下的數據流向,稱為單向數據流。