我正在尝试从MatchState中的MatchScoreboard对象中选择homeScore和awayScore
export const selectScoreboard = (state: MatchState) => state.scoreboard;
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);
我的状态结构:
export interface MatchScoreboard {
awayScore: number;
homeScore: number;
}
export interface MatchState {
scoreboard: MatchScoreboard;
}
export const initialState: MatchState = {
scoreboard: {
awayScore: 0,
homeScore: 0,
}
};
选择器调用
store.pipe(select(selectHomeScore));
store.pipe(select(selectAwayScore));
此方法有效,但对我来说还不够干净
store.pipe(select('matchState', 'scoreboard', 'homeScore'));
store.pipe(select('matchState', 'scoreboard', 'awayScore'));
当我尝试使用选择器时,我收到以下代码行中未定义homeScore和awayScore的错误
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);
状态已正确更改,除了通过选择器获取数据之外,其他一切都很好
答案 0 :(得分:1)
与使用字符串选择器一样,必须首先选择matchState
,因为scoreboard
存在于matchState
中。
export const selectMatchState = (state: GlobalStatate) => state.matchState;
// or
export const selectMatchState = createFeatureSelector('matchState')
现在您可以这样做:
export const selectScoreboard = createSelector(selectMatchState, selectScoreboard)
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);