Handling one property effecting the state of anoth

2019-09-17 16:18发布

问题:

How do we handle the scenario where a change in the state of one property affects the state of another?

Here's the actual scenario that may help clarify the problem I'm trying to solve.

I have a general purpose date picker component which can be used as a completely independent component or it can be "linked" to another instance of date picker.

I use this "linked" approach whenever I need the user to set two dates e.g. start and end dates. The idea is that when the user sets the start date, I want to disable all the dates prior to the start date the user has just set in the second date picker. This way, user cannot accidentally set an end date that is prior to the start date.

Each date picker is an object in my reducer with a few properties. So it looks something like this:

datePickers: {
   "startDatePicker": {
      activeDate: "8/24/2017",
      disableBefore: "",
      disableAfter: ""
   },
   "endDatePicker": {
      activeDate: "8/25/2017",
      disableBefore: "8/24/2017", // Notice that the disableBefore is set to the active date in startDatePicker
      disableAfter: ""
   }
}

Setting a property's values in an object is easy enough but I'm running into an interesting problem.

As I said, my date picker can be used as a single and independent date picker in which case we will NOT set the disable dates of another date picker instance.

The problem is whenever I use a "linked" instance and try to set the disable date of the second date picker, the action used to set the date creates a problem in reducers with date pickers that are NOT linked. Because all reducers respond to the same action, a reducer with an independent instance of date picker still respond to the action and tries to set the disable date of a date picker that does NOT exist.

One idea I had was to use a condition in the reducer but I do feel that's a bad idea. Here's where I asked the question and I agree with the answer. Conditions in reducers

回答1:

I believe you have some way to uniquely identify a datepicker in the store.

What I would do is have the action for updating a datepicker also have a field that identifies which other datepicker this one is linked to.

That way I can dispatch two actions from my action creator (I'm thinking Redux Observable, but I believe it is possible with Redux Thunk as well): one to update this datepicker, another to update the linked datepicker.

That would just leave the store with the task of updating the datepicker, and not worry about the logic.