简体   繁体   中英

What is the proper way to have a copy of redux state on a component prop

I have something like this:

  ngOnInit() {
    this.reduxServiceHandle = this.reduxService.subscribe(() =>
      this.reduxUpdates()
    );
  }

  reduxUpdates(): void {
    const newState: TransportationControlTowerState = this.reduxService.getState();
    // Check if feature groups object has changed
    if (!isEqual(this.groups, newState.groups)) {
      ...
      this.groups = newState.groups;
    }
  }

This is my reducer:

case TransportationControlTowerActions.ADD_GROUP:
  return newState = {
    ...state,
    groups: { ...state.groups, [payload.groupId]: payload.group }
  };
  break;

So, my question is: Do I need to clone deep the state before save it on this.groups prop? this.groups = newState.groups;

I think that every time I change the redux state, I return a new state object so there won't be a problem with my local state(this.groups) pointing to the old state.

But I just want to make sure I am not following any anti pattern.

Regards,

Official Redux docs says:

State is read-only

The only way to change the state is to emit an action, an object describing what happened.

This ensures that neither the views nor the network callbacks will ever write directly to the state. Instead, they express an intent to transform the state.

You can view full list of core principles here https://redux.js.org/introduction/three-principles

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