Heim > Fragen und Antworten > Hauptteil
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;