NGXS在setState中传播状态

时间:2019-06-02 07:48:39

标签: angular ngxs

import { State, Action, StateContext } from '@ngxs/store';

export class FeedAnimals {
  static readonly type = '[Zoo] FeedAnimals';
}

export interface ZooStateModel {
  feed: boolean;
}

@State<ZooStateModel>({
  name: 'zoo',
  defaults: {
    feed: false
  }
})
export class ZooState {
  @Action(FeedAnimals)
  feedAnimals(ctx: StateContext<ZooStateModel>) {
    const state = ctx.getState();
    ctx.setState({
      ...state,
      feed: !state.feed
    });
  }
}

我正在从gitbook学习ngxs,上面是从那里复制的代码块。 在此实例...state中分配给对象。为什么我们需要这个?因此我们只有一个对象属性供稿,并且已经分配了feed: !state.feed

1 个答案:

答案 0 :(得分:0)

您需要使用... state,因为您要修改当前状态的状态

使用传播运算符进行复制操作,以便将先前的状态复制到新的状态对象,并在新创建的状态对象中修改数据。

const a = [1, 2, 3]

const b = [...a, 4, 5, 6] =>  [1, 2, 3, 4, 5, 6]

这段代码

...state,
feed: !state.feed

您正在制作状态对象的新副本并修改状态对象内的feed属性