简体   繁体   中英

How to store multiple copies of a certain state in redux

It should be noted that I am using Redux with React-Native.

For simplicity sake, lets say I have an email viewer. There's a homepage with a massive list of emails and when you tap on an email, you are navigated to another screen. Here, the contents of the email, title, subject, body, is all held in a piece of state managed by redux. This all works fine.

Lets say I back out of that page, and now navigate to another email. The previous email pops up for a split second before the new email is shown. It should be noted here that I am storing the data in AsyncStorage as a sort of "cache?". The issue here is that since I only re-update the state whenever I tap on an email, the state which is the body of the email viewing page gets updated a split second after the user is navigated to it. This, is annoying.

The heart of the question is this

How can I store the body of my data in another piece of state, functionally identical to the current-email-viewing-state without overwriting the currently active state?

or

is this even the best way to do this?

Thanks

You could use Redux's lifecycle methods to handle this. Let's say the state for your email detail component looks something like this:

export const initialState: StateShape = {
  loading: false,
  readOnlyEmailData: {
    recipientEmails: null,
    senderEmail: null,
    body: null,
  },
};

When the email detail component (let's call it EmailDetail.jsx) is loading, you can use ComponentDidMount() to get and set your values.

You'll probably have actions and actionCreators like getEmail, getEmailSuccess, and getEmailError. Set loading to true in getEmail, and then false again on success or error. You can add a conditionally rendered spinner component (easy to borrow from something like MaterialUI) to EmailDetail, which is visible only when loading is true, and render the rest of your content when loading is false.

When the user hits the back button or otherwise navigates away from the component, componentWillUnmount() can be given a list of things to do as the component prepares to unmount. In this case you could use a reset method to reset loading and readOnlyEmailData to initial state on unmount.

When the user clicks on a new email, it will load the new email data on mount and show the spinner until the new email data is available.

There are other ways to do this, this is not the most optimized, but it should work quite a bit better than what you've tried so far. I hope it helps:)

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