出现“Angular Ngrx 8选择器错误:无法读取未定义属性'map'。”错误通常是由于选择器函数返回了未定义值而引起的。在 @ngrx/store
中,选择器函数必须返回有效的值。
以下是可能导致此错误的代码示例以及解决方法:
import { createSelector } from '@ngrx/store';
const selectFeature = (state) => state.feature;
export const selectFeatureData = createSelector(
selectFeature,
(feature) => feature.data.map(item => item.name)
);
解决方法:
feature.data
的空值检查,确保它是一个有效数组。Array.isArray()
或 feature.data && Array.isArray(feature.data)
进行检查。修改后的代码示例:
import { createSelector } from '@ngrx/store';
const selectFeature = (state) => state.feature;
export const selectFeatureData = createSelector(
selectFeature,
(feature) => feature.data && feature.data.map(item => item.name)
);
import { createSelector } from '@ngrx/store';
const selectFeature = (state) => state.feature;
export const selectFeatureData = createSelector(
selectFeature,
(feature) => feature.data.map(item => item.name)
);
解决方法:
feature.data
是否为数组,并且确保它不是空数组。Array.isArray()
和 feature.data.length > 0
进行检查。修改后的代码示例:
import { createSelector } from '@ngrx/store';
const selectFeature = (state) => state.feature;
export const selectFeatureData = createSelector(
selectFeature,
(feature) => Array.isArray(feature.data) && feature.data.length > 0 ? feature.data.map(item => item.name) : []
);
通过检查选择器函数返回的值,并确保返回的值是有效的,可以解决“无法读取未定义属性'map'”的错误。