题目
有如下代码:
import React, { useEffect, useState } from 'react'
export const TestingComponentsPage: React.FC = () => {
const [a, setA] = useState(0)
const bAll = useState(0)
const [c, setC] = useState(0)
useEffect(() => {
console.log('a_changed')
}, [a])
useEffect(() => {
console.log('b_changed')
}, [bAll[0]])
useEffect(() => {
console.log('bAll_changed')
}, [bAll])
return (
<>
<button onClick={() => setA(a + 1)}>setA</button>
<button onClick={() => bAll[1](bAll[0] + 1)}>setB</button>
<button onClick={() => setC(c + 1)}>setC</button>
</>
)
}
请问:点击 setA setB setC 三个按钮时,分别会输出什么内容?为什么?
答案
- 点击 setA 时会输出:a_changed,bAll_changed
- 点击 setB 时会输出:b_changed,bAll_changed
- 点击 setC 时会输出:bAll_changed
分析
核心问题是:useEffect
deps 参数的判定原理是什么?
参考资料:https://juejin.cn/post/6844904175579447304