Is using getState in Redux an anti-pattern?

2020-03-17 02:55发布

问题:

I'm using Redux for the first time in a jQuery application and I have created small observable implementation. The observables are responding to changes on multiple properties of the state object, making changes to the DOM when state itself changes. If my observable callback needs 2 property values to accomplish its task, I will observe both values and then use those values to update the UI. The observables don't touch the state at all. They just present it to the observable in a callback so it can be used to update the UI with the state.

The project I'm working on is a refactor so I'm adding Redux after the fact. At times, I realize I need a specific state property in a piece of code that I may not have the time to properly refactor into an observable. In those instances, I call getState on the store to get what I need and move on with it. I can't help feeling like this approach is a little flawed.

Is using store.getState where ever I need it considered an anti-pattern? Are their explicit use-cases that I should avoid when using store.getState?

回答1:

When you use store.getState() too liberally, you end up passing around the global state to random components. You run the risk of introducing coupling between components and parts of your state that have nothing to do with one another, which is anti-pattern. You should only call getState for two reasons: to fetch the initial state of the app, and in the update logic for your store -i.e inside your store.subscribe() callback.

As far as your observables go, in a typical component based view layer such as React, the only thing you really need to observe in a redux app is the entire application state as a whole, not individual pieces of it. Changes to the state as a whole are subscribed to and trickle down from the top level component.

However since you are refactoring a Jquery application I think your use of observables is acceptable. There is a library called reselect that you can use for this purpose if you don't feel like rolling your own. It helps you to compute state from arbitrary parts of the global state and provides efficient memoization so same inputs don't get recomputed.

At times, I realize I need a specific state property in a piece of code that I may not have the time to properly refactor into an observable. In those instances, I call getState on the store to get what I need and move on with it. I can't help feeling like this approach is a little flawed.

One easy drop-in solution you could implement in cases like this is to use event emitters in your reducers to propagate pieces of the global state to the specific Jquery components that need them. This will keep you from having to pass around global state, preserving component isolation.