在 React Redux 中传播状态
spread state in react 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,
};
}
};
如果我一开始使用这个减速器,它会成功所以 success
将是 true
,error
将是 null
。但是,如果第二次失败并且我在这种情况下使用 ...state
,那么成功值是多少?它是初始值 (false
) 还是保留第一个请求的值 (true
)?
这就是所谓的 spread operator,它基本上允许您将一个对象的字段“克隆”到一个新对象中。
在您的示例中,{ ...state, error: action.err }
表示“从 state
复制所有字段,但将字段 error
设置为 action.err
”。对于这种你想更改很少的字段但又想保留原始数据的逻辑非常方便。
我想知道{ ...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,
};
}
};
如果我一开始使用这个减速器,它会成功所以 success
将是 true
,error
将是 null
。但是,如果第二次失败并且我在这种情况下使用 ...state
,那么成功值是多少?它是初始值 (false
) 还是保留第一个请求的值 (true
)?
这就是所谓的 spread operator,它基本上允许您将一个对象的字段“克隆”到一个新对象中。
在您的示例中,{ ...state, error: action.err }
表示“从 state
复制所有字段,但将字段 error
设置为 action.err
”。对于这种你想更改很少的字段但又想保留原始数据的逻辑非常方便。