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

React中ComponentDidMount正常但点击按钮渲染子组件报错

问题分析与解决方案

首先咱们来揪出报错的核心原因:当你点击edit按钮获取单个用户详情时,Contact组件里的fetchUser状态从空数组变成了单个用户对象,但GetDetailsContentSection组件里依然在调用map()方法——而对象是没有map方法的,这就直接导致了渲染报错。

下面给你两种可行的解决思路:

方法1:保持fetchUser始终为数组类型

修改Contact组件里的handleChange方法,把获取到的单个用户对象包装成数组,这样子组件的map方法就能正常工作了:

handleChange(id){
 console.log(id);
 fetch('https://jsonplaceholder.typicode.com/users/'+id)
 .then(response => response.json())
 .then(data => this.setState({ fetchUser: [data] })); // 将单个对象存入数组
}

方法2:在子组件中做兼容处理

如果不想修改状态结构,可以在GetDetailsContentSection组件里先判断数据类型,兼容数组和对象两种情况:

import React from "react"
class GetDetailsContentSection extends React.Component {
 render(){
 const { data } = this.props;
 // 统一把数据转换成数组格式,空数据时返回空数组
 const renderData = Array.isArray(data) ? data : data ? [data] : [];

 return(
 <div>
 <p>This is the details of particular contact selected</p>
 <ul>
 { renderData.map(item=>{
 return(<li key={item.id}>{item.name}</li>)
 }) }
 </ul>
 </div>
 )
 }
}
export default GetDetailsContentSection

额外优化小建议

  • 可以给GetDetailsContentSection加个空状态提示,比如未选中用户时显示“请选择一个用户查看详情”,提升体验;
  • 给fetch请求加上错误捕获,避免请求失败时状态异常:
handleChange(id){
 console.log(id);
 fetch('https://jsonplaceholder.typicode.com/users/'+id)
 .then(response => {
   if(!response.ok) throw new Error('请求失败');
   return response.json();
 })
 .then(data => this.setState({ fetchUser: [data] }))
 .catch(err => console.error(err)); // 捕获并打印错误
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:12:52