简体   繁体   English

React tsx 渲染间隔更改列表

[英]React tsx Render Intervally changing list

I wanna make a Game that some items are keep falling from top and if click them it disappear and raise the score.我想做一个游戏,一些项目不断从顶部掉下来,如果点击它们,它就会消失并提高分数。

but I cannot see the items.但我看不到这些项目。

I use the setInterval to push the random items into the list intervally.我使用 setInterval 将随机项目间隔推送到列表中。 And render the items list.并渲染项目列表。

if I put a fixed list, it shows the items but 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.在控制台中,DgArray 不断添加。

and I found using the breakpoint in Dg component that it goes to the Dg component, but it goes not to return even in the component.我发现使用 Dg 组件中的断点会转到 Dg 组件,但即使在组件中也不会返回。

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.您的问题很可能是您的IonPage (我假设它是为渲染子级而设计的)在DgArray更改时不知道重新渲染,因为它位于任何组件的 state 之外。

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.解决此问题的一种方法是将DgArray设置为新组件的 state (可能包装您的IonPage以便您可以使用相同的DgArray.map )并使用setIntervalsetDgArray传递给您的组件以在那里更新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM