从 Reducer 调用选择器
Call a selector from Reducer
我可以使用减速器中的选择器吗?
我有一个类似的代码:
case Action Types.ACTION: {
const loading = getIsLoading(state)
return {
atribute1: false,
attribute2: action.payload,
}
}
default: {
return state;
}
}
}
export const getState = createFeatureSelector<State>('feature');
export const getIsLoading = createSelector(
getState,
state => state.loading
);
当我最初发送一个动作时,我得到了这样的错误:“无法读取未定义的 'loading'。
我的错误在哪里?我的方法有问题吗?
就像我在评论中所说的那样:最好不要在状态中复制信息。如果你需要在 reducer 中调用选择器,它看起来像你我会这样做的。
您可以通过创建第三个更高阶的减速器来避免这样做,该减速器将 return 现有减速器中需要的任何东西。
所以你有了 getIsBusy reducer,你创建了另一个 reducer,它只会 return 来自你的状态的新数据,你想要读取的 isBusy:
export const getAttribute = createSelector(
getState,
state => state.attribute
);
现在您有 getIsBusy 和 getAttribute 作为选择器,您可以创建第三个选择器,您可以在其中放置您需要的任何逻辑:
export const getHigherOrderSelector = createSelector(
getIsBusy,
getAttribute,
(isBusy, data) => {
return { isBusy, data };
// Or whatever other processing you might want to do here
}
);
我可以使用减速器中的选择器吗?
我有一个类似的代码:
case Action Types.ACTION: {
const loading = getIsLoading(state)
return {
atribute1: false,
attribute2: action.payload,
}
}
default: {
return state;
}
}
}
export const getState = createFeatureSelector<State>('feature');
export const getIsLoading = createSelector(
getState,
state => state.loading
);
当我最初发送一个动作时,我得到了这样的错误:“无法读取未定义的 'loading'。
我的错误在哪里?我的方法有问题吗?
就像我在评论中所说的那样:最好不要在状态中复制信息。如果你需要在 reducer 中调用选择器,它看起来像你我会这样做的。
您可以通过创建第三个更高阶的减速器来避免这样做,该减速器将 return 现有减速器中需要的任何东西。
所以你有了 getIsBusy reducer,你创建了另一个 reducer,它只会 return 来自你的状态的新数据,你想要读取的 isBusy:
export const getAttribute = createSelector(
getState,
state => state.attribute
);
现在您有 getIsBusy 和 getAttribute 作为选择器,您可以创建第三个选择器,您可以在其中放置您需要的任何逻辑:
export const getHigherOrderSelector = createSelector(
getIsBusy,
getAttribute,
(isBusy, data) => {
return { isBusy, data };
// Or whatever other processing you might want to do here
}
);