我們可以通過變更 `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