题目

有如下代码:

  1. import React, { useEffect, useState } from 'react'
  2. export const TestingComponentsPage: React.FC = () => {
  3. const [a, setA] = useState(0)
  4. const bAll = useState(0)
  5. const [c, setC] = useState(0)
  6. useEffect(() => {
  7. console.log('a_changed')
  8. }, [a])
  9. useEffect(() => {
  10. console.log('b_changed')
  11. }, [bAll[0]])
  12. useEffect(() => {
  13. console.log('bAll_changed')
  14. }, [bAll])
  15. return (
  16. <>
  17. <button onClick={() => setA(a + 1)}>setA</button>
  18. <button onClick={() => bAll[1](bAll[0] + 1)}>setB</button>
  19. <button onClick={() => setC(c + 1)}>setC</button>
  20. </>
  21. )
  22. }

请问:点击 setA setB setC 三个按钮时,分别会输出什么内容?为什么?

答案

  1. 点击 setA 时会输出:a_changed,bAll_changed
  2. 点击 setB 时会输出:b_changed,bAll_changed
  3. 点击 setC 时会输出:bAll_changed

    分析

    核心问题是:useEffect deps 参数的判定原理是什么?
    参考资料:https://juejin.cn/post/6844904175579447304