I want to make a Game where some items are falling from the top and if they are clicked they disappear and raise the score, but I cannot see the items.
I use the setInterval to push the random items into the list at intervals and render the items list.
If I put a fixed list, it shows the items but all at the same time. I want the items to keep adding in continuously. It's okay to not use the interval. I just don't know the other way.
codes:
var DgArray:string[] = []
const [sec, setSec] = useState();
const time: any = useRef(10);
const timerId: any = useRef('startTimer');
useEffect(() => {
timerId.current = setInterval(() => {
setSec(time.current);
time.current -= 1;
console.log(time.current)
DgArray.push(RandomKind()) //RandomKind returns a string
console.log(DgArray)
}, 1000);
return () => clearInterval(timerId.current);
}, []);
if (time.current <= 0) {
console.log("TimeOut");
clearInterval(timerId.current);
}
}, [sec]);
the return
<IonPage className="Game">
<h1 id="startTimer">{Number((sec / 10).toFixed(0))}</h1>
{ DgArray.map((value, idx) => <Dg kind={value} DgNum={idx}></Dg>)}
</IonPage >
in console, the DgArray is keep adding.
and I found using the breakpoint in Dg component that it goes to the Dg component, but it does not return even in the component.
CodePudding user response:
Your problem is likely that your IonPage (which I will assume is designed to render children) does not know to re-render when DgArray changes because it is outside of the state of any component.
One approach to fix this would be to have DgArray be the state of a new component (possibly wrapping your IonPage so you can use the same DgArray.map) and you pass in setDgArray to your component with setInterval to update it there.
