state (狀態(tài))
與 props (屬性) 相似,但 state 是私有的,只屬于當前組件。
1. 狀態(tài)的定義、使用與更新
class Hello extends React.Component {
constructor (props) {
super(props);
// 定義狀態(tài)
this.state = {
name: 'hello'
}
}
render () {
// 通過 this.state 使用狀態(tài)
return (
<div>
<h1>hello, { this.state.name }</h1>
{/* 通過調用 this.setState 來修改狀態(tài) */}
<button onClick={ () => { this.setState({ name: 'world' }) } }>修改name</button>
</div>
)
}
}
上面代碼中,
- 通過在
constructor中設置this.state來定義狀態(tài)。
并且constructor是唯一能夠初始化狀態(tài)的地方。
constructor必須使用super()調用基礎構造函數。 - 通過
this.state.xxx來使用某個狀態(tài)。 - 通過
this.setState()來修改狀態(tài)。
2. 正確的使用狀態(tài)
- 不要直接更新狀態(tài)
- 狀態(tài)更新可能是異步的
- 狀態(tài)更新合并
PS
- 函數定義的組件又叫無狀態(tài)組件,so,想給某個組件添加狀態(tài),需要使用類組件的方式
生命周期
1. 生命周期圖解

image.png
2. 生命周期介紹
- constructor(props) - 構造函數
- componentWillMount() - 組件掛載之前
- render() - 渲染
- componentDidMount() - 組件掛載完成
- componentWillReceiveProps(nextProps) - 組件接收到新屬性前調用
-
shouldComponentUpdate(nextProps, nextState)- 我是否應該要更新呢 - componentWillUpdate(nextProps, nextState) - 組件更新之前
- componentDidUpdate(prevProps, prevState) - 組件更新完成
- componentWillUnmount() - 組件卸載之前
3. 通過 shouldComponentUpdate(nextProps, nextState) 來處理一些性能問題
組件的某一些狀態(tài)或屬性的改變可能不需要進行頁面的更新。此時在
shouldComponentUpdate()中返回false即可。