如何优化这段React数组映射条件渲染代码?
优化方案
你这段代码的多分支条件判断可以用映射表来简化,不仅代码更清爽,以后要加新类型也不用改一堆if-else,直接扩展映射表就行。
第一种优化写法(最直观)
export default function Landing({ arr }) { // 把判断规则做成键值对,一目了然 const contentMap = { "Whatever": "whatever", "Whichever": "whichever", "Another": "another" }; return arr.map((item, index) => { // 遍历映射表,找到匹配的文本 const matchedEntry = Object.entries(contentMap).find(([targetVal, displayText]) => { // 把目标值转成驼峰(比如"Whatever"转成"whatEver")去匹配对象属性 const propName = targetVal.charAt(0).toLowerCase() + targetVal.slice(1); return item[propName] === targetVal; }); // 有匹配就用对应文本,没有就用默认的"whoever" const text = matchedEntry ? matchedEntry[1] : "whoever"; return <p key={index}>{text}</p>; }); }
第二种写法(如果属性和文本有规律)
要是你的对象属性名(比如whatEver)和对应的显示文本(whatever)刚好是“驼峰转全小写”的关系,还能再简化:
export default function Landing({ arr }) { // 只需要列出所有要匹配的目标值 const targetValues = ["Whatever", "Whichever", "Another"]; return arr.map((item, index) => { const matchedVal = targetValues.find(val => { const propName = val.charAt(0).toLowerCase() + val.slice(1); return item[propName] === val; }); const text = matchedVal ? matchedVal.toLowerCase() : "whoever"; return <p key={index}>{text}</p>; }); }
额外提醒
- 尽量别用数组索引当
key,如果数组里的每个对象有唯一的id之类的字段,用那个当key更好,能减少React不必要的重渲染,避免一些奇怪的bug。 - 以后要加新的判断类型,比如再加个
a.someThing === "Something",第一种写法就在contentMap里加个"Something": "something"就行,完全不用碰循环里的逻辑,维护起来特别方便。
内容的提问来源于stack exchange,提问作者Don
相关产品推荐
相关产品推荐

