useContext 不会在回调中更新其值



>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])
}

相关内容

  • 没有找到相关文章

最新更新