React-hooks-useState
useState的基本用法
格式:
const [state, setState] = useState(initialState);
初始狀態
- useState的第一個參數是初始狀態
讀取狀態
- 當useState(initialState)被調用時返回一個數組
- 該數組的第一項是狀態值
const stateArray = useState(false);
stateArray[0]; // false => 狀態值
更新狀態
- 用值更新狀態
const [state, setState] = useState(initialState);
// 改變狀態值 設置新的值
setState(newState);
// 之后渲染新的值
- 使用回調函數更新狀態
- 使用回調更新裝填,可以解決setState引發異步更新和狀態合并
const [state, setState] = useState(initialState);
setState(prevState => nextState);
- 示例
// Toggle a boolean
const [toggled, setToggled] = useState(false);
setToggled(toggled => !toggled);
// Increase a counter
// 推薦使用回調的方式更新組件狀態
const [count, setCount] = useState(0);
setCount(count => count + 1);
console.log(count) // 1
setCount(count => count + 1);
console.log(count) // 2
// Add an item to array
const [items, setItems] = useState(["old"]);
setItems(items => [...items, 'New Item']);
初始值狀態計算
- 計算組件的初始狀態很慢。這在類組件中不是問題,因為初始狀態計算僅在構造函數中發生一次,但是在函數組件中,初始狀態計算在render函數中聲明,并且在每次渲染時都發生。因此,緩慢的初始狀態計算會大大降低整個應用程序的速度。
useState(/* Slow computation */)
- useState 還可以將函數作為參數而不是值作為參數,并且該函數將僅在首次呈現組件時運行。通過使用此功能的版本,useState您將不再在每次渲染時運行緩慢的計算,而是像類組件一樣在組件的第一個渲染中僅運行一次。
使用useState()的陷阱
- 使用useState()鉤子時,只能在函數頂層調用掛鉤
- 不能在循環,條件,嵌套函數中使用useState()調用
- 在多次調用中,調用以相同的順序
- useState()只能在函數式組件中調用,不能在class類中使用
- 不可以在嵌套函數中調用
注意點示例
可以多次調用useState(),調用以相同的順序
function Bulbs() {
// Good
const [on, setOn] = useState(false);
const [count, setCount] = useState(1);
// ...
}
無效調用useSate()
- 在if語句中,錯誤的調用
function Switch({ isSwitchEnabled }) {
if (isSwitchEnabled) {
// Bad 錯誤用法
const [on, setOn] = useState(false);
}
// ...
}
- 在嵌套函數中被錯誤的調用
function Switch() {
let on = false;
let setOn = () => {};
function enableSwitch() {
// Bad
[on, setOn] = useState(false); }
return (
<button onClick={enableSwitch}>
Enable light switch state
</button>
);
}