如何比对对象key对应的数组值与Redux id,为变量赋值className?
错误原因
- 你当前的判断逻辑存在本质错误:
reduxState.common.id是单个数值,listOfIds是数组,直接用!=对比两者永远返回true,所以你的className会始终被赋值为hidden - 你调用的
_.map没有返回值,遍历处理的结果没有被保存下来,无法后续使用
正确实现
首先优化useSelector的取值逻辑,只取需要的id避免不必要的组件重渲染,然后用数组的includes方法判断id是否存在于目标数组中:
// 仅从redux取需要的id,不要取整个state减少不必要重渲染 const commonId = useSelector(state => _.get(state, 'common.id', null)); // 遍历Headers生成带className的新数组 const headerList = _.map(Headers, item => { const { listOfIds } = item; // 兼容listOfIds为空的场景+判断id是否匹配数组内任意元素 const isMatched = listOfIds?.includes(commonId) ?? false; const className = isMatched ? '' : 'hidden'; // 返回处理后的项可直接用于渲染 return { ...item, className } })
如果你偏好使用lodash的方法做存在性判断,可以把判断逻辑替换为_.includes(listOfIds, commonId),效果完全一致。
内容的提问来源于stack exchange,提问作者Shaun
相关产品推荐
相关产品推荐

