简体   繁体   中英

How to handle multiple stores of same type in Flux / ReactJS?

I'm new to Flux/React and I'm having a hard time understanding some of the fundamental architecture decisions:

  1. I know all stores are meant to be singletons, but are they all created at app start, or can the lifetime of a store be smaller, specific to the user's actions?
  2. Can I have multiple instances of the same store type, each initialized with a different context?

Unfortunately, all the examples I've seen seem too simplistic to answer these questions. Let's start with Facebook's chat app example . There are multiple threads each with messages. MessageStore holds all the messages for the entire app and a method called getAllForThread(id) returns a filtered subset of messages. When a message comes into ANY thread, it emits a change notification that causes the MessageSection react component to re-fetch data (regardless of which thread the user is viewing). This obviously doesn't scale. What if we had 10,000 threads each with lots of message activity? Here's how I decided to solve the issue:

  1. Each MessageStore is initialized with a thread id.
  2. Create a singleton MessageStoreFactory that creates and manages MessageStores.
  3. When the user clicks on a thread, instead of the React component subscribing to a global MessageStore, it asks the MessageStoreFactory for the MessageStore for that specific thread.
  4. If the factory already has a MessageStore for that thread, it returns it. Otherwise it creates one, kicks off an async task to fetch the initial data for it, and returns it.
  5. When the React component is torn down (let's say the user navigates away from it), it notifies the Factory that it's all done with the Store. Using reference counting or some other cache logic would allow the Factory to prune unused stores.

How far off base am I with this approach? Is there a simpler approach that still scales?

It seems easier to make smarter data fetching according to the thread which user is viewing. Could I see this facebook's example at some blog-post or presentation?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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