You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回的temperament字符串中的逗号替换为竖线?

解决Dog API中temperament字符串替换失败的问题

问题核心是部分狗品种的temperament属性不存在(值为undefined),直接调用replaceAll会触发TypeError,导致整个替换逻辑失效;而修改name能生效是因为所有品种都包含name属性。

前端组件修复方案

在卡片渲染时先判断temperament是否存在,再执行替换,同时注意匹配API返回的, (逗号+空格)分隔符,避免出现多余空格:

return(
    <div className="container">
        <img src={image} width="80px" height="80px" alt=""/>
        <h2>{name}</h2>
        <h3>{temperament ? temperament.replaceAll(', ', ' | ') : '无性格描述'}</h3>
        <h3>{weight}</h3>
        <h3>{!!createInDb ? "true" : "false"}</h3>
    </div>
)

后端处理修复方案

遍历数据时先校验temperament的存在性,同时补上变量声明避免全局污染:

let dog = dogs.data.map(el =>{
    const temp = el.temperament ? el.temperament.replaceAll(', ', ' | ') : '无性格描述';
    return{
        id: el.id,
        name: el.name,
        weight: el.weight.metric,
        height: el.height.metric,
        temperament: temp,
        image: el.image.url,
        life_span: el.life_span
    }
})

你可以在控制台打印dogs.data验证,比如Mexican Hairless这类品种的temperament字段为undefined,之前的代码因遇到这类数据报错中断,加上存在性判断后即可正常处理所有数据。

内容的提问来源于stack exchange,提问作者GuerreroEnier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:48:08