P粉9211651812023-08-15 09:11:27
我建立了兩個獨立的useEffect區塊,其中一個只是初始化容器和firework物件! 感謝大家的幫忙!
import './App.css'; import React, { useRef } from 'react'; import {useEffect, useState} from 'react'; import Fireworks from 'fireworks-js'; function App() { const delay = ms => new Promise(res => setTimeout(res, ms)) const fireworks = useRef(); useEffect(()=>{ const container = document.getElementById('fireworks-container'); fireworks.current = new Fireworks(container); }, []); const [count, setCount] = useState(0); function handleClick() { setCount(count+1) console.log('button pressed' + count); } useEffect(()=>{ console.log('effect called' + count); fireworks.current.launch(10); fireworks.current.launch(20); makeRequest(); async function makeRequest() { await delay(200); fireworks.current.launch(20); await delay(300); fireworks.current.launch(20); } }, [count]); return ( <div className="App"> <h1 className = "text">Fireworks App</h1> <button onClick={handleClick}>Restart</button> <div id = 'fireworks-container' style = {{width: '100%', height: '100vh'}}/> </div> ); } export default App;