Reactjs 如何跨函数调用在react函数中保留timerID?

Reactjs 如何跨函数调用在react函数中保留timerID?,reactjs,Reactjs,秒表是游戏的一个子项,它传递一个表示是否轮到X的布尔值。因此,我的秒表在每次滴答声和每次移动后都会重新渲染。我想根据此值启动和停止秒表。我的问题是clearInterval()没有停止滴答声 const tick = () => { setElapsedTime(((Date.now() - startingTime) / 1000).toFixed(2)); } const timerID = useRef(); React.useEffect(() =>

秒表是游戏的一个子项,它传递一个表示是否轮到X的布尔值。因此,我的秒表在每次滴答声和每次移动后都会重新渲染。我想根据此值启动和停止秒表。我的问题是clearInterval()没有停止滴答声

  const tick = () => {
    setElapsedTime(((Date.now() - startingTime) / 1000).toFixed(2));
  }
  const timerID = useRef();

  React.useEffect(() => {

    if (props.xIsNext) {
    timerID.current = setInterval(
      () => tick(),
      50
    );
    }
    else {clearInterval(timerID.current, []); setElapsedTime(0);}
    return () => {
      clearInterval(timerID.current, []);
    };
  }, [props.xIsNext])

  return (
    <article className="clock">
      <div>
        <h1>Stopwatch for player X</h1>
        <h2>Time: {elapsedTime}</h2>
        <h2>It is X's turn: {JSON.stringify(props.xIsNext)}</h2>
      </div>
    </article>
  );

}
const tick=()=>{
setElapsedTime(((Date.now()-startingTime)/1000).toFixed(2));
}
const timerID=useRef();
React.useffect(()=>{
如果(下一个道具){
timerID.current=setInterval(
()=>勾选(),
50
);
}
else{clearInterval(timerID.current,[]);setElapsedTime(0);}
return()=>{
clearInterval(timerID.current,[]);
};
},[props.xIsNext])
返回(
运动员X的秒表
时间:{elapsedTime}
轮到X了:{JSON.stringify(props.xIsNext)}
);
}

React.useffect(()=>{/*..*/},[])
尝试在useffect中添加空数组。我添加了[props.xIsNext],使useffect在tic-tac-toe游戏中每隔一回合运行一次。