简体   繁体   中英

Redux state outside redux's store

I've a situation where my react-native application has some images that I want to show,

export const myImages = Map()
  .set('image-one, {
    name: 'Foo',
    source: require('./foo'),
  })
  .set('image-two, {
    name: 'Bar',
    source: require('./bar'),
  })

I let my user to select the kind of image in question, like so:

export const selectImageSaga = function*({ imageId }) {
  yield put({ type: 'SELECT_IMAGE', imageId /* image-one, image-two, etc. */})

Now, in my store, I have a reference to the image that I want to show. I could call myImages.get(reduxState.imageId) to get the data that I want, all good and great. I really hate this.

Now both my saga and my react components need to refer to an external and (potentially, I'm not showing this in this example) mutable object to fetch the data they need when they need it.

If it wasn't for source , I would simply store the path or uri of the file I'm interested, and that's it, I would keep all my state in redux.

What are my alternatives here?

There's no magic here, I see 3 main avenues of action:

  1. Your action sends over all the necessary information. That can be done by moving the responsibility to the caller of the action, or the action creator itself will fetch the data from the external potentially mutable object, normalize it, and pass it to the reducer.
  2. Your reducer gets the ID from the action, and combines it with the external object. Again, this means that the redux store has all of the necessary information.
  3. Your selector (or if you don't have selectors, your react component) accepts the ID and combines it with your external object. This works well if you do things like persist your store into localStorage (because then you only persist the ID, not all of the information)

The advantage of 1 is that your reducer is stupid and stateless, the logic of fetching the relevant info is done in the action creator.

The advantage of 2 is that... well, I honestly can't think of too many, let me know if you find one.

The advantage of 3 is that your store remains relatively small and simple, which helps with things like server-side rendering and localStorage persistence. But in turn, it makes your React components less pure.


There's no silver bullet here I'm afraid, you will need to make the decision based on your project's needs and conventions.

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