[英]spread state in react redux
I want to know what does ...state
inside { ...state }
do?我想知道什么呢
...state
内{ ...state }
呢? Is it to change the value of the store to the initial value or to let the store be the latest value?是将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,
};
}
};
If at first I use this reducer, it'll be successful so success
will be true
and error
will be null
.如果一开始我使用这个减速器,它会成功,所以
success
将为true
, error
将为null
。 But if it fails the 2nd time and I use ...state
in this situation, what is the success value?但是如果它第二次失败并且我在这种情况下使用
...state
,那么成功值是多少? Is it the initial value ( false
) or does it keep the value from the first request ( true
)?它是初始值 (
false
) 还是保留第一个请求中的值 ( true
)?
That is called the spread operator and it basically allows you to "clone" the fields of one object into a new object.这称为扩展运算符,它基本上允许您将一个对象的字段“克隆”到一个新对象中。
In your example, { ...state, error: action.err }
means "copy all fields from state
, but set the field error
to action.err
".在您的示例中,
{ ...state, error: action.err }
表示“从state
复制所有字段,但将字段error
设置为action.err
”。 It's very handy for this kind of logic where you want to change a very few fields but otherwise want to keep the original data.对于您想要更改很少字段但又想要保留原始数据的这种逻辑,它非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.