React接口数据控制台输出正常但渲染报错Received NaN for `children` 如何解决?
问题核心原因
你收到的警告和渲染失败是因为字符串拼接过程中产生了NaN,React不允许直接把NaN作为子元素渲染,因此抛出警告且不会展示内容。
产生NaN的常见场景:
response.data里的name/address/city三个字段中存在undefined/null/数值类型的取值,参与加法运算时出现了非法计算- 还有一种常见可能:你接口返回的
response.data本身是商铺数组,而不是单个商铺对象,直接取response.data.name就会得到undefined,拼接后最终得到NaN
排查步骤
先在axios回调中打印确认返回值结构,确认字段名是否正确、返回值是对象还是数组:
Axios.get(url).then((response) => { // 打印完整结构确认 console.log('完整返回值:', response.data) console.log('三个字段值:', response.data.name, response.data.address, response.data.city) })
修复方案
方案1:如果返回的是单个商铺对象
给每个字段加兜底空值,用模板字符串自动处理类型转换,避免非法运算:
const getShop = () => { Axios.get(url).then((response) => { // ?? 运算符判断字段为undefined/null时用空字符串兜底 const showText = `${response.data.name ?? ''}${response.data.address ?? ''}${response.data.city ?? ''}` showShop(showText) }) }
方案2:如果返回的是商铺数组
修改state类型为数组,遍历渲染所有商铺:
// 初始化state为数组 const [shopList, setShopList] = useState([]) const getShop = () => { Axios.get(url).then((response) => { setShopList(response.data) }) } // 渲染部分修改为遍历 <Box sx={{ "& > :not(style)": { m: 1, width: "25ch" }, }} > {/* 遍历渲染所有商铺 */} {shopList.map(shop => ( <span key={shop.id}>{shop.name} {shop.address} {shop.city}</span> ))} <Button onClick={getShop}>List all Shops</Button> <Button onClick={() => showShopCard(false)}>Close</Button> </Box>
内容的提问来源于stack exchange,提问作者Miloš Milutinov
相关产品推荐
相关产品推荐

