useState()
useState()
import React, { useState } from 'react'
[state, setState] = useState(initialValue)
回傳陣列
[現在值, 更新函式]
setter需引入函式,而非值
setState((currentValue) => currentValue + 1)
1. 整合有關的state
如果你總是同時更新2個或以上的state,考慮將其整合成一個單獨的state
2. 避免state互相矛盾
3. 避免冗餘的state
4. 避免state內的重複
5. 避免過深巢狀的state
更新
code:javascript
let updatedValue = {};
updatedValue = { "item1": "newValue" };
setData(data => ({
...data,
...updatedValue
}));
新增
code:javascript
setData(data => ({ ...data, "item1": "newValue" }));
也可更新巢狀物件
setData(data => ({ ...data, data.nestedProperty.value: "newValue" }))
移除
code:javascript
let copyOfObject = { ...data }
setData(data => ({
...copyOfObject
}));