Skip to content

函数组件里的闭包陷阱.md

jsx
function countReducer(state, action) {
  switch (action.type) {
    case 'add':
      return state + 1
    case 'minus':
      return state - 1
    default:
      return state
  }
}

const [count, dispatchCount] = useReducer(countReducer, 0)
jsx
// 更新count
const handleButtonClick = useCallback(()=>dispatchCount({type:'add'}), [])

// 弹出显示count
const handleAlertBtnClick = function() {
    setTimeout(() => {
      alert(count)
    }, 2000)
  }

// 两个按钮
<Child config={config} onButtonClick={handleButtonClick}></Child>
<button onClick={handleAlertBtnClick}>alert</button>

问题是这样的,先点弹出count,在等待的两秒期间,点击按钮更新count,等弹出count时显示的count值为两秒前点击按钮的那一刻的值

解决方案

jsx
const countRef = useRef()
countRef.current = count

const handleAlertBtnClick = function() {
    setTimeout(() => {
      alert(countRef.current) // 注意所用的变量
    }, 2000)
  }

最后更新:

苏ICP备20040768号