简体   繁体   English

如何多次渲染同一组件并且所有实例具有相同的状态

[英]How to render multiple times the same component and all instances have the same state

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? 有任何想法吗?

Thank you! 谢谢!

If you don't want to implement Redux for this you can make use of a singleton. 如果您不想为此实现Redux,则可以使用单例。 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. 您甚至可以使单例仅返回当前状态,并让您的组件处理其余的倒计时。

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. 最后,最简单的方法是将其置于最高组件的状态,然后通过props将其传递给所有组件。

What I'm trying to say is that there are a lot of ways to do this without implementing Redux. 我要说的是,有很多方法可以在不实现Redux的情况下完成此操作。 Redux will be the nicest, but is often overkill for what you are using it for. Redux会是最好的,但是对于您使用它的目的来说往往过于矫kill过正。

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

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