javascript - Setting state inside a callback function when using hooks
问题描述
I am writing a component for my pinball game. I have to setState inside the function triggered by the 'on contact' listener. But state is not updating. Is there another design that i can try?
function Pinball(){
const[score, setScore] = useState(0);
useEffect(()=>{
//... here I set physics environment and have variable world
world.on('begin-contact', function(contact){
//...
setScore( score + 1 );
})
}, []);
return (<span>{score}</span>);
}
解决方案
您可以使用useCallback
回调处理程序,并使用 useEffect 设置 'begin-contact' 事件侦听器。您必须像这样传递依赖项:
function Pinball(){
const[score, setScore] = useState(0);
const handleBeginContact = useCallback(function(contact){
setScore( score + 1 );
}), [score] );
useEffect(()=>{
world.on('begin-contact', handleBeginContact);
}, [world])
return <span>{score}</span>;
}
您可以像这样进一步简化 setScore 事件:
setScore(score => score+1)
然后您不必传递分数依赖项。
此外,正如 Dan Pantry 在评论中所说,您将希望在 useEffect 中返回一个函数,该函数取消注册 'begin-contact' 事件侦听器,例如return () => world.off('begin-contact')
,但这将取决于您对world
.
推荐阅读
- html - 使用 HTML5 限制电子邮件末尾点(@ 之前)的模式
- python - 运行 python3 darknet_video.py 时出错
- c++ - 错误 LNK2001:未解析的外部符号(SFML 库的每个静态成员都无法加载)
- azure-devops - 如果有人删除整个 azure devops 组织,是否有灾难恢复策略计划?
- javascript - 如何创建唯一键/用 array.push 替换其值?
- rst2pdf - 使用 rst2pdf 一次包含多个图像
- sql - Presto比较两个日期并添加条件
- c# - 编辑器中的全屏模式游戏视图
- angular - 我的 Angular 项目无法加载显示错误相关的内容安全策略
- java - 无法从 GitLab 包注册表下载 Maven 依赖项