1月 24, 2020 React
我們可以通過變更 `state` 或 `props` 的內容來更新 render 的結果。但有些情況如果當 Component 又可以通過 `state` 來更新,又同時可以通過 `props` 來更新的話,那麼需要怎樣做呢?

### 使用 `state` 更新 render

先看看下面的 Code,我們可以通過把 `props` 傳的的資料 assign 到 `state`,然後在 render 時讀取 state 便可了。這樣傳入的 `props` 可以從 `state` 反映出來。

```js
/**
 * my component
 */
class MyComponent extends React.Component {
	
	constructor(props) {
	
		super(props);
		
		this.state = {
			
			text: this.props.text
		};
	}

	render() {
		
		return this.state.text;
	}
}
```

不過上面有一個缺點,就是 `constructor` 只會在建立 Component 時運行一次,在往後的 `props` 更新時,Component 並不會把 `props` 的內容再一次 assign 到 `state`。這讓便不能反映出日後 `props`變更的值。

### 解決方法

我們可以加入一個方法,來把 `props` 的變更重新 assign 到 `state`,使 render 出來的結果合乎預期。

```js
/**
 * my component
 */
class MyComponent extends React.Component {
	
	constructor(props) {
	
		super(props);
		
		this.state = {
			
			text: this.props.text
		};
	}

	componentDidUpdate(oldProps) {
	
		if( oldProps.text !== this.props.text ) {
			
			this.setState(state => ({
				
				...state,

				text: this.props.text
			}));
		}
	}

	render() {
		
		return this.state.text;
	}
}
```

我們可以通過在 `componentDidUpdate` 中檢查需要的 `props` 內容有沒有變更,從而決定是否發動 `setState`,這樣就可以把 `props` 的更新反映出來。

在 React 的官方網站對這個動作也有特別說明 :  
https://zh-hant.reactjs.org/docs/react-component.html#constructor
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)