useState 的参数可以有两种形式:
useState(普通的数据)
=> useState(0) / useState(‘abc’)
useState(回调函数)
=> useState(() => { return 初始值 })
回调函数的返回值就是状态的初始值
该回调函数只会触发一次
const [list, setList] = useState(() => {
return JSON.parse(localStorage.getItem('comments')) || comments
})
使用 回调函数 来为 useState 初始化默认值
回调函数的返回值就是状态的初始值!
注意:该回调函数只会触发一次
该使用哪种形式?
- 如果状态就是一个普通的数据(比如,字符串、数字、数组等)都可以直接使用
useState(普通的数据)
- 如果状态是经过一些计算得到的,此时,推荐使用
useState(回调函数)
第一种:
const [list, setList] = useState(
JSON.parse(localStorage.getItem('list')) || arr
)
可以转化为:
const initList = JSON.parse(localStorage.getItem('list')) || comments
const [list, setList] = useState(initList)
这种情况下,只要组件更新,此处的 localStorage 等操作就会重复执行
第二种 :
const [list, setList] = useState(() => {
return JSON.parse(localStorage.getItem('comments')) || comments
})
这种方式,因为回调函数只会执行一次,所以,此处的 localStorage 等操作代码只会执行一次
在这种情况下,推荐使用第二种方式