首页 > 解决方案 > 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>);

}

标签: javascriptreactjs

解决方案


您可以使用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.


推荐阅读