終於來到挑戰的1/2了
這次要來稍微說明下React hook跟元件生命週期
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
元件生命週期(Component Life Cycle)共可分如下三(四)大階段
• Mounting (Initialization)建立初期
• Updating (Updation)更新時期
• Errors (Errors Handing)有錯發觸發時期
• Unmounting (Destruction)銷毀時期
可以到component目錄新增一個LifeCycle.js進行測試
import React, { Component } from 'react'
export default class Lifecycle extends Component {
constructor() {
super();
console.log('constructor: used to initialize default values to state fields.');
this.state = {
name: '',
users: []
}
}
componentDidMount() {
console.log('componentDidMount:Used to call backed service/api to initialize state data');
fetch('https://api.github.com/users')
.then(res => res.json())
.then(data => {
this.setState({ users: data });
})
}
shouldComponentUpdate(newProps, newState) {
console.log('shouldComponentUpdate: check changes in props and state');
return this.state.users !== newState.users; //true/false
}
render() {
console.log('render: Render the UI.');
return (
<div>
<h2>Life Cycle Hooks</h2>
<ul>
{
this.state.users.map((item, index) => {
return <li key={index}>{item.login}</li>
})
}
</ul>
</div>
)
}
componentWillUnmount() {
console.log('componentWillUnmount: clear all subscriptions or clean resouces');
}
componentDidCatch(error, errorInfo) {
console.log('componentDidCatch: Handle Error');
}
}
運行結果如下
constructor(): 在 React 組件掛載之前,會調用它的構造函數。
componentDidMount():在該 class 建構完組件(更新後)的時候被執行。一般來說call api時機會是在 componentDidMount
componentDidUpdate():觸發的時機就是當 state 改變之後,若shouldComponentUpdate回傳false,那麼 componentDidUpdate 也不應該被觸發!
componentWillUnmount():組件實例卸載後,將永遠不會重新加載它。
shouldComponentUpdate():當 props 或 state 發生改變時,shouldComponentUpdate() 會在render()之前被觸發。
render(): render() 方法是元件中唯一必運行的方法。
以三大階段去拆分會依序執行到的function
1.Mount :初始元件
constructer()
render()
componentDidMount()
2.Updating :在透過setState、或者props一有更新時後
shouldComponentUpdate() => 若return false,就不會繼續往下運行
render()
componentDidUpdate()
3.Unmounting :Component 銷毀
componentWillUnmount()
render()
React Hook 提供的API方法
• useState - Use to maintain state in the functional component. Exposes the current state, and a function to update the state.
• useEffect - Similar to componentDidMount, componentDidUpdate, and componentWillUnmount. Run once on the component mount, or many times when another state is updated.
• useContext - Enables integration with React Context API.
• useReducer - Exposes state and dispatch functions that are similar to the
Redux flow.
一樣新增Hook.js元件
import React, { useEffect, useState } from 'react'
export default function Hooks() {
const [user, setUser] = useState({ name: '' });
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://api.github.com/users')
.then(res => res.json())
.then(data => {
setUsers(data);
});
})
const handleChange = function (e) {
setUser({ name: e.target.value });
}
return (
<div>
<h2>Hooks: {user.name}</h2>
<input type="text" value={user.name} onChange={handleChange} />
<h2>Users</h2>
<ul>
{
users.map((item, index) => {
return <li key={index}>{item.login}</li>
})
}
</ul>
</div>
)
}
useEffect 中一樣去做api存取只在第一次作業並間接呼叫useState進行Users陣列初始化
而handleChange這個會隨著input onchange及時更動的callback function
間接呼叫useState來更新state 而使user單一筆即時連動