如何在不更改没有新值的属性的情况下更新对象的状态?
How do I update the state on an object without changing the properties that do not have a new value?
我有这个减速器。
case UPDATE_ENDPOINT:
return <IState>state.map(endpoint =>
endpoint.ocid === action.endpoint.ocid
? {
...endpoint,
name: action.endpoint.name,
hostname: action.endpoint.hostname,
origin: action.endpoint.origin,
originType: action.endpoint.originType,
originValidation: action.endpoint.originValidation,
}
: endpoint
);
假设在我的 action payload 中我只有 endpoint.name
和 endpoint.hostname
,那么 reducer 会将 payload 中未传递的值设置为 undefined
。如何让 reducer 只更新 action payload 中的值,而将不在 action payload 中的值保持不变?
最简单的方法是使用 object-spread 语法:
case UPDATE_ENDPOINT:
return <IState>state.map(endpoint =>
endpoint.ocid === action.endpoint.ocid
? {
...endpoint,
...action.endpoint
}
: endpoint
);
我有这个减速器。
case UPDATE_ENDPOINT:
return <IState>state.map(endpoint =>
endpoint.ocid === action.endpoint.ocid
? {
...endpoint,
name: action.endpoint.name,
hostname: action.endpoint.hostname,
origin: action.endpoint.origin,
originType: action.endpoint.originType,
originValidation: action.endpoint.originValidation,
}
: endpoint
);
假设在我的 action payload 中我只有 endpoint.name
和 endpoint.hostname
,那么 reducer 会将 payload 中未传递的值设置为 undefined
。如何让 reducer 只更新 action payload 中的值,而将不在 action payload 中的值保持不变?
最简单的方法是使用 object-spread 语法:
case UPDATE_ENDPOINT:
return <IState>state.map(endpoint =>
endpoint.ocid === action.endpoint.ocid
? {
...endpoint,
...action.endpoint
}
: endpoint
);