>useConext
值在附加到事件的回调中没有更新wheel
。我试图控制台,但仍然打印静态值。但在回调之外,它正在打印更新的值
const Home = () => {
//accessing my context
var [appState, dispatch] = useContext(CTX);
//printing updated value here (working perfect here)
console.log(appState);
//my callback on wheel event (also using debouce to queue burst of events)
var fn = debounce(e => {
//incrementing value ++1
dispatch({ type: 'INCREMENT_COMPONENT_COUNTER' });
//printing static value here (problem here)
console.log(appState);
}, 500);
//setting and removing listener on component mount and unmount
useEffect(() => {
window.addEventListener('wheel', fn);
return () => {
window.removeEventListener('wheel', fn);
};
}, []);
};
挂载时,侦听器使用函数变量进行初始化,该函数变量将appStore
的第一个值括在其词法范围内。
请参阅闭包。
若要修复它,请将其移动到useEffect
范围内。
const Home = () => {
const [appState, dispatch] = useContext(CTX);
useEffect(() => {
const fn = debounce(e => {
dispatch({ type: 'INCREMENT_COMPONENT_COUNTER' });
console.log(appState);
}, 500);
window.addEventListener('wheel', fn);
return () => {
window.removeEventListener('wheel', fn);
};
}, [appState]);
};
友情忠告:
- 像
eslint
一样使用棉绒 - 它应该警告您在useEffect
内部使用appState
- 不要使用
var
- 它容易出错。
你的debance函数在每次渲染中都会发生变化,而useEffect只捕获了第一个渲染,你可以使用useCallback来解决这个问题:
const Home = () => {
// accessing my context
const [appState, dispatch] = useContext(CTX)
// printing updated value here (working perfect here)
console.log(appState)
// my callback on wheel event (also using debouce to queue burst of events)
const fn = useCallback(
() =>
debounce(e => {
// incrementing value ++1
dispatch({ type: 'INCREMENT_COMPONENT_COUNTER' })
// printing static value here (problem here)
console.log(appState)
}, 500),
[appState, dispatch],
)
// setting and removing listener on component mount and unmount
useEffect(() => {
window.addEventListener('wheel', fn)
return () => {
window.removeEventListener('wheel', fn)
}
}, [fn])
}