# 狀態 state
state 是一個組件的內部狀態,不能通過外部干擾改變state的值。
我們創建一個獲取當前時間的組件:
```jsx
import React, { Component } from 'react';
const style = {
color: '#f00'
};
class App extends Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div style={style}>
<h2>現在是 {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default App;
```
先不用理會 `componentDidMount`、`componentWillUnmount`、`tick`,這些是React的生命周期函數。
我們看看構造函數,繼承了父類的 `props`,這里可以看到有一個 state 的屬性,用來存儲組件的內部狀態,調用的時候使用 `this.state.[xxx]`。
## 初始化state
需要在類的構造器 `constructor` 中初始化state,可以通過 `props` 獲取外部傳入的數據,也可以傳入初始化值。
```js
constructor (props) {
this.state = {
count: props.initValue || 0,
num: 0
}
}
```
## 不能直接更新狀態
構造函數是唯一能夠初始化 this.state 的地方。其他地方不能直接改變 state 的值。
例如,此代碼不會重新渲染組件:
```js
this.state.comment = 'Hello';
```
如果直接對 state 進行重新賦值,控制臺會收到一個警告:
>[warning] warning Do not mutate state directly. Use setState() react/ no- direct- mutation- state
而應當使用 `setState()` 改變state的狀態 :
```js
this.setState({comment: 'Hello'});
```
## 不要通過上一個狀態計算下一個狀態
因為 this.props 和 this.state 可能是異步更新的,你不應該依靠它們的值來計算下一個狀態。
例如,以下代碼可能無法更新計數器:
```js
this.setState({
counter: this.state.counter + this.props.increment,
});
```
要修復它,請使用第二種形式的 setState() 來接受一個函數而不是一個對象。 該函數將接收先前的狀態作為第一個參數,將此次更新被應用時的props做為第二個參數:
```js
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
```
- 簡介
- 第一章 React入門
- 1.1 創建一個React項目
- 1.2 組件
- 1.3 JSX
- 1.4 eject
- 1.5 渲染
- 第二章 React組件
- 2.1 組件定義
- 2.2 數據處理
- 2.2.1 props
- 2.2.2 state
- 2.3 生命周期
- 2.3.1 裝載過程
- 2.3.2 更新過程
- 2.3.3 卸載過程
- 2.4 事件處理
- 2.5 條件渲染
- 2.6 列表渲染
- 第三章 React高級
- 3.1 靜態類型檢查
- 3.1.1 flow
- 3.1.2 typescript
- 3.2 React Developer Tools
- 第四章 Redux狀態管理
- 4.1 安裝與配置
- 4.2 一個簡單的計數器開始
- 4.3 Store
- 4.3.1 獲取state
- 4.3.2 subscribe
- 4.4 Action
- 4.4.1 Action Creators
- 4.5 Reducer
- 4.5.1 Reducer 的拆分
- 4.6 與其他狀態管理工具的對比
- 第五章 React-Router路由
- 參考資料