期望在新代碼中使用hooks
函數 + hooks = 有‘生命週期’的組件
與class的區別:
Hook 提供了強大而富有表現力的方式來在組件間複用功能,自定義hook
const [originData, setStateData] = useState(0);
const newData = originData * 2;
setStateData(newData);
//
useEffect(()=>{}, []) // 第一個參數是 回調函數,第二個參數是 依賴項。
// 回調函數 在組件第一次render和之後的每次update後運行,React保證在DOM已經更新完成之後纔會運行回調
// 依賴項 當配置了狀態依賴項後,只有檢測到配置的狀態變化時,纔會調用回調函數。
// 數據獲取,設置訂閱以及手動更改 React 組件中的 DOM 都屬於副作用
// 一些react class 生命週期的執行 ,在hooks中都可以使用 useEffect()實現
// 清除/不清除 定時器 ,訂閱外部數據源 =》 清除
// 裝飾器不可用於函數式組件,如果需要包裹,
// export default Form.create()(View)
Hooks 方法 對應 Class 生命週期
Class | Hooks |
---|---|
constructor | useState 初始化state |
getDerivedStateFromProps | useEffect + other(useState) |
shouldComponentUpdate | useMemo |
render | 函數本身 |
componentDidMount | useEffect + other |
componentDidUpdate | useEffect + other |
componentWillUnmount | useEffect + other |
componentDidCatch | 無 |
getDerivedStateFromError | 無 |
React 16.3新週期函數
componentWillReceiveProps(props) => UNSAFE_componentWillReceiveProps(props)
static getDerivedStateFromProps
:該函數在掛載階段和組件更新階段都會執行,即每次獲取新的props
或 state
之後都會被執行,在掛載階段用來代替componentWillMount
;在組件更新階段配合 componentDidUpdate
,可以覆蓋componentWillReceiveProps
的所有用法。
同時它是一個靜態函數,所以函數體內不能訪問 this
,會根據 nextProps
和 prevState
計算出預期的狀態改變,返回結果會被送給 setState
,返回 null
則說明不需要更新 state
,並且這個返回是必須的。
componentWillReceiveProps(nextProps) {
const { value } = nextProps;
const { detail } = this.state;
if (JSON.stringify(value) == JSON.stringify(detail)) return;
this.setState({ detail: value }, () => {
this.calculateTotal();
});
}
---------> 16.3 新週期
static getDerivedStateFromProps(nextProps, prevState) {
const { value: detail } = nextProps;
// 當傳入的type發生變化的時候,更新state
if (
JSON.parse(JSON.stringify(detail)) !==
JSON.parse(JSON.stringify(prevState.detail || []))
) {
return {
detail,
};
}
// 否則,對於state不進行任何操作
return null;
}
componentDidUpdate() {
this.calculateTotal();
}
-------> Hooks
const [detail, setDetail] = useState([]);
useEffect(() => {
setDetail(value);
calculateTotal(value);
}, [value]);
// 只要value有更新,就setDetail