反应 redux 中的传播状态

问题描述

我想知道 ...state 里面的 { ...state } 有什么作用?是将store的值改为初始值还是让store为最新值?

import * as actionType from "../actions/actionTypes";

const initialStore = {
  roomsCount: 0,resPerPage: 0,rooms: [],filteredRooms: 0,error: null,success: false,};

const reducer = (state = initialStore,action) => {
  switch (action.type) {
    case actionType.ALL_ROOM_SUCCESS:
      return {
        ...state,success: true,rooms: action.rooms,roomsCount: action.roomsCount,resPerPage: action.resPerPage,filteredRooms: action.filteredRooms,};
    case actionType.ALL_ROOM_Failed:
      return {
        ...state,error: action.err,};
  }
};

如果我一开始使用这个 reducer,它会成功,所以 success 将是 trueerror 将是 null。但是如果它第二次失败并且我在这种情况下使用 ...state,那么成功值是多少?它是初始值 (false) 还是保留第一个请求 (true) 中的值?

解决方法

这称为 spread operator,它基本上允许您将一个对象的字段“克隆”到一个新对象中。

在您的示例中,{ ...state,error: action.err } 表示“复制 state 中的所有字段,但将字段 error 设置为 action.err”。这种逻辑非常适合您希望更改很少的字段但又希望保留原始数据的逻辑。