1

在我的应用程序中,我有许多仅在用户登录时才有意义的状态部分。

当用户登录并直接导航到页面时,路由器会显示该页面但必须进行异步调用,因此尚未填充状态的一部分。

现在,假设我必须在导航栏上显示一个按钮,该按钮必须占据状态的一部分,但是自从异步调用完成后,这个状态就没有被填充。

更实用的是,我有这个选择器:

export const getSelectedCustomer = state => state.systems.selectedCustomer;

有了这个就没有问题了,因为selectedCustomerinitialStatereducer的一部分

问题出在这个选择器中:

export const getSelectedCustomerName = state => {
    return state.systems.entities[getSelectedCustomer(state)].customer;
}

entities状态的一部分initialState是一个空数组,将在异步调用时填充。

因此,当应用程序启动并且我映射(使用 connect - mapStateToProps)选择器时,getSelectedCustomerName我收到错误,因为entities它是空的并且可以肯定,customer字段不存在

如果采取一些简单的解决方案if-else,但我将不得不在应用程序的“每个”部分执行此操作。

我在问是否有更好的解决方案来避免这种情况......

4

1 回答 1

2
const NullCustomerEntities = {
    customer: "Anonymous"
}

export const getSelectedCustomer = state => state.systems.selectedCustomer;

export const getCustomerEntities = state => {
    return state.systems.entities[getSelectedCustomer(state)] || NullCustomerEntities;
}

export const getSelectedCustomerName = state => {
    return getCustomerEntities(state).customer;
}

这是Null Object 模式 的经典示例(希望您不介意 Ruby 中的代码)。

于 2016-06-27T00:56:14.413 回答