vendredi 22 juillet 2016

React: how to pass component identity to Redux state

Is it safe to pass this to Redux action creator from withing component defined using React.createClass?

I have defined the following reducer:

const unsavedChangesProtectionReducer = handleActions({
    [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsavedChangesProtection, action) => ({protected: true}),
    [DISABLE_UNSAVED_CHANGES_PROTECTION]: (unsavedChangesProtection, action) => ({protected: false})},
    {protected: false}
)

Multiple components may set/unset the global state.unsavedChangesProtection.protected flag, and problem arises from unsetting this flag, as component shouldn't unset it if some other component has set it before this component.

One solution is to check if flag is already set and if not, set it, store the info about component setting the flag in component's internal state, and unset it if internal state states that component has set the flag. However, this violates the DRY principle, as I have to introduce exactly same login in every component.

More generalized solution would be to store the identity of the component which lastly mutated the global state as a member of state itself, so each component can see from the state if it's their change and unset in accordingly. Is this possible to implement in React, as each component are re-initialized when mounted/unmounted

Aucun commentaire:

Enregistrer un commentaire