代码之家  ›  专栏  ›  技术社区  ›  Aragorn

国家到底在做什么[[副本]

  •  -1
  • Aragorn  · 技术社区  · 6 年前

    ...state 在下面的例子中,我不能完全理解。我搜索了它,一般理解为传播,但不知道为什么数据属性在 Interface State 重复出现在 return{} 减速器挡块 switch ,作为。。。将 传播

    export interface State {
      sessionData: Map<string, string>;
      requesting: boolean;
      hasError: boolean;
      status: StatusModel;
    }
    
    export function sessionReducer(state: State = INITIAL_STATE, action: Session.Actions): State {
          switch (action.type) {
            case Session.REQUEST_SESSION_DATA:
              return {
                ...state,
                requesting: true,
                hasError: false,
                status: undefined,
              };
          }
    }
    

    附言:我已经看过线了 here 返回{} …状态 以及另外三个属性。

    4 回复  |  直到 6 年前
        1
  •  2
  •   Elias Garcia    6 年前

    状态的关键是它是不可变的(返回一个新对象,而不是一个修改过的对象)。所以,如果你想修改状态添加新的值到它你需要返回当前状态加上新的值你想添加到以前的状态。在这个例子中使用了spread操作符 ... ,则返回一个新的不可变对象,该对象包含以前的状态和三个新属性 requesting , hasError status . 你可以考虑这样做:

    export function sessionReducer(state: State = INITIAL_STATE, action: Session.Actions): State {
          switch (action.type) {
            case Session.REQUEST_SESSION_DATA:
              state.requesting = true;
              state.hasError: false;
              state.status: undefined;
    
              return state;
          }
    }
    

    但你不能这样做,因为你打破了国家的哲学,新的不可变的对象,而不是修改的:)

    在你的例子中,我们需要知道 INITIAL_STATE sessionData 财产。所以,在这个例子中,返回 加上剩下的财产。

    在角度上,使用 Redux 图案与 OnPush @Input 而不是逐个属性比较对象。这是性能上的一大优势。

    Use of Spread Operator with Redux

        2
  •  1
  •   PlayMa256    6 年前

    ... spread operator .

    return {
        ...state,
        requesting: true,
        hasError: false,
        status: undefined,
    };
    

    return {
        sessionData: state.sessionData,
        requesting: state.requesting,
        hasError: state.hasError
        status: state.status,
        requesting: true,
        hasError: false,
        status: undefined,
    };
    
        3
  •  0
  •   Mike Cluck    6 年前

    你说得对,这是 spread operator . 基本上,它提取给定对象的所有属性。另一种写作方式是:

    let newState = {
      sessionData: state.sessionData,
      requesting: state.requesting,
      hasError: state.hasError,
      status: state.status
    };
    newState.requesting = true;
    newState.hasError = true;
    newState.status = undefined;
    return newState;
    

    换一种说法

    { ...state }
    

    做一个浅薄的拷贝 state

        4
  •  0
  •   danday74    6 年前

    这意味着返回一个包含state所有属性的新对象,并添加/修改3个附加属性。

    值得知道的是 {...state} 极为平等 state 以便:

    _.isEqual(state, {...state}) // returns true
    

    {...state} !== state
    

    这是因为 {} 创建一个新对象,而“展开”操作符只是向该对象添加道具。因此,状态的对象引用与新对象引用不同。这就是变化检测的工作原理。它查看对象引用是否已更改。如果有,它就知道有变化,并相应地采取行动。之所以使用这种方法,是因为它比检查深度相等(即必须检查所有属性)要快得多。

    在只想修改状态的一个属性的情况下,reducer通常使用spread操作符。如果他们这样做了:

    state.requesting = true
    return state
    

    为了加强变更检测,有一个很棒的小lib叫做 ngrx-store-freeze