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

React报错:computerProtectionPlanState.map is not a function 修复方案

修复React中电脑保护计划单选按钮的TypeError错误

错误根源

你将JSON格式的字符串赋值给了期望是数组的computerProtectionPlanState状态,而字符串没有map方法,因此触发TypeError: computerProtectionPlanState.map is not a function。手动拼接的protectionPlans是字符串,并非真正的JS数组/对象。


修复方案

1. 修复数据获取函数

放弃手动拼接字符串的方式,直接构建JS对象数组:

const [computerProtectionPlanState, setComputerProtectionPlanState] = useState([]);

const getProtectionPlansFromDb2 = async (productId) => {
    const URL = `${variables.API_URL_ADDONS}/${productId}`;
    const response = await fetch(URL);
    const AddOns = await response.json();

    // 筛选对应productId的保护计划,收集add_On字段
    const plansList = AddOns
        .filter(plan => plan.productId === productId)
        .map(plan => plan.add_On);

    // 构造符合渲染逻辑的结构:数组包含一个对象,键为p+productId,值为分号拼接的计划字符串
    const protectionPlans = [{
        [`p${productId}`]: plansList.join(';')
    }];

    setComputerProtectionPlanState(protectionPlans);
}

2. 优化渲染逻辑(处理空数据与无效项)

原代码中split(";")会因末尾分号生成空字符串,添加过滤逻辑避免无效单选按钮:

{(pickupMessageOrProtectionPlans(cart.pickupOnOrOffPic, cart.shipOnOrOffPic, cart.productId) === "Protection Plans") ? 
    <div>
        {computerProtectionPlanState.map((item, index) => (
            <div key={index}>
                {item[`p${cart?.productId}`]?.split(";")
                    .filter(plan => plan.trim() !== "") // 过滤空字符串
                    .map(toDo => (
                        <div key={toDo}>
                            <input 
                                type="radio" 
                                name={`p${cart?.productId}`} 
                                value={toDo} 
                                onChange={() => changeID(toDo)} 
                            />
                            {toDo}
                        </div>
                    ))}
            </div>
        ))}
    </div> : ""}

额外注意事项

  • 确保接口返回的AddOns是数组格式,若不是需先做类型校验
  • 若cart?.productId可能为空,需在渲染前增加判断,避免生成pundefined这类无效键名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:33:32