我有一个简单的状态记录:
interface StateParams {
priceObj: PriceDTO;
}
const defaultState = {
priceObj: undefined,
}
class State extends Record(defaultState) implements StateParams {
priceObj: PriceDTO;
}
默认情况下它具有未定义的值。
无论发生什么,因为 offerRequest 被保存到 priceObj
而不是转换为不可变的
(state: State, priceObj: PriceDTO) => state.set('priceObj', priceObj),
我也有简单的选择器:
export const getQuoteId = (state: State): string | undefined =>
state.getIn(['offerData', 'priceObj'], {}).offerID;
不幸的是它抛出了一个错误:
未捕获的类型错误:无法读取 null 的属性“offerID”
有什么特别的原因,为什么 getIn
在这种情况下不返回 notSetValue
值?
最佳答案
状态包含键 priceObj
,因为您通过 reducer 中的 set 操作添加了它。 notSetValue
仅在 map 不包含键时返回。显式 null
是有效值(undefined
也是如此),因此未返回 {}
。
您应该在设置状态之前检查 priceObj != null
或使您的选择器类似于:
export const getQuoteId = (state: State): string | undefined =>
(state.getIn(['offerData', 'priceObj']) || {}).offerID;
关于javascript - 不可变的 getIn 返回 null 但不返回 notSetValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45295459/