How to Handle UI State in Redux/React - Redux-UI?

2019-05-30 13:49发布

问题:

I am researching into what is the best way to store the UI state, Should I use something like Redux-UI (https://github.com/tonyhb/redux-ui) to store/manage the UI state? or should I create my own actions/reducers for the UI?

Also... when I have stored the UI state, how do I make sure if the browser is refreshed, I still have exactly the same state of the page? Just as a normal web page would including Data taken from the server.

I have Redux with thunk middle wear implemented and a store. I have worked with React for the past couple of months thus far.

Thanks! Quinton

回答1:

Our team has spent some days on this. The reasons we want UI states, instead of putting those states to Redux's state tree, can be:

  1. Those UI states are only relevant to a very small number of components. But yet sometimes we need to share those states amongst them. For example, a Button to control a Modal, they both need to read/write the 'isModalOpen' state.

  2. Those states are not data, they are UI preference and it is fine to reset them to the default upon component unmount. Persisting them in the single Redux store sounds like polluting the state tree.

We tried:

  1. Creating a separate redux state tree just for UI.
  2. Add a main branch, say 'state.UI' for all 'UI' states.

However, all these involve having to use/implement custom middleware, actions and reducers. Hard.

At the end, I made react-provide-state. It works really well. The only drawback of it is your can not easily see the ui states like states in Redux tree in browser console. And you can only update states through UI (user action event callbacks). That's fair, it is UI states we are talking about.