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

为什么我们把扩散算子用于redux

  •  0
  • Mizlul  · 技术社区  · 7 年前

    我看到了以下代码:

    export default function productReducer(state = initialState, action) {
        switch(action.type) {
            case FETCH_PRODUCTS_BEGIN:
                return {
                    ...state,
                    loading: true,
                    error: null
                };
    
            case FETCH_PRODUCTS_SUCCESS:
                return {
                    ...state,
                    loading: false,
                    items: action.payload.products
                };
    
            case FETCH_PRODUCTS_FAILURE:
                return {
                    ...state,
                    loading: false,
                    error: action.payload.error,
                    items: []
                };
    
            default:
                return state;
        }
    }
    

    但不明白为什么我们每次都要用……陈述每一个案例。

    我们不能只写:

    return {
                        loading: false,
                        error: action.payload.error,
                        items: action.payload.products
                    };
    

    有人能解释吗?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Pipe    7 年前

    因为通常你想把其他钥匙留在你的状态中…

    如果您所在的州有:

    {
       items:['a', 'b', 'c'],
       loading: false,
       error: null
    }
    

    您只返回例如:

    case FETCH_PRODUCTS_BEGIN:
        return {
            // ...state, --> Without this line
            loading: true,
            error: null
        };
    

    你的新州将是

    {
        loading: true,
        error: null
    }
    

    你的 items 将丢失。

    然后,返回:

    case FETCH_PRODUCTS_BEGIN:
        return {
            ...state,
            loading: true,
            error: null
        };
    

    你在说

    返回状态的副本,但重写 loading error “钥匙”

        2
  •  1
  •   Yaroslav Bigus    7 年前

    这是为了用新的或更新的值创建新的复制状态对象(如果没有这个,您将需要手动指定每个状态字段)。

    Object.assign 可作为备选方案

    Redux Docs 对使用扩散算子有很好的解释。