AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
官方原话是:useEffect、useMemo、useCallback都是自带闭包的。每一次组件的渲染,它们都会捕获当前组件函数上下文中的状态(state, props),所以每一次这三种hooks的执行,反映的也都是当前的状态,你无法使用它们来捕获上一次的状态。 1. 调用更新时传递函数解决 ``` setData(value+1)->setData(value=>value+1) ``` 2. 使用useRef ``` const ref = useRef(); ref.current = value; useEffect(() => { let timer = setInterval(() => { setData(ref.current + 1) }, 1000); return () => { clearInterval(timer); } }, []); ``` 3. useReducer ``` function reducer(count, action) { switch (action.type) { case 'add': return count + action.gap; default: return count; } } function Demo() { const [count, dispatch] = useReducer(reducer, 0); useEffect(() => { let timer = setInterval(function() { dispatch({type: 'add', gap: 10}); }, 1000); return () => { clearInterval(timer); } }, []); return ( <p>{count}</p> ); } ```