如何多次渲染同一个组件并且所有实例都具有相同的状态 [英] How to render multiple times the same component and all instances have the same state

查看:45
本文介绍了如何多次渲染同一个组件并且所有实例都具有相同的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计数器组件作为道具在我的应用程序的不同屏幕的各种组件中传递.我想要成功的是在不同屏幕上继续倒计时.我现在所取得的成就是在每个场景中开始倒计时.有什么想法吗?

I have a counter component being passed as prop in various components in different screens of my app. What I want to succeed is the countdown to continue in the different screens. What I have achieved now is to start a countdown in each sceen. Any ideas?

谢谢!

推荐答案

如果您不想为此实现 Redux,您可以使用单例.在这个单例中,您有一个可以用事件发射器扩展的类.只需以您想要的时间间隔发出具有当前状态的事件.

If you don't want to implement Redux for this you can make use of a singleton. In this singleton you have a class that you can extend with an event emitter. Just emit the event with the current state at your desired interval.

您甚至可以创建一个单例,它只是简单地返回当前状态并让您的组件处理倒计时的其余部分.

You could even make a singleton that just simply returns the current state and let your component handle the rest of the countdown.

最后,最简单的方法是将它置于最顶层组件的状态,然后通过 props 将其传递给所有组件.

Lastly, the easiest way would to have it in the state of your top most component and just pass it down to all the components through props.

我想说的是,有很多方法可以在不实施 Redux 的情况下做到这一点.Redux 将是最好的,但通常对于您使用它的目的来说太过分了.

What I'm trying to say is that there are a lot of ways to do this without implementing Redux. Redux will be the nicest, but is often overkill for what you are using it for.

这篇关于如何多次渲染同一个组件并且所有实例都具有相同的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆