React异步请求后this.state.plans变量未定义及渲染报错问题求助
问题根因
- 字段名不匹配:接口返回的
response.data中存储计划列表的字段是paymentPlans,你最初代码中用const { plans } = response.data解构取值,字段名不对应自然拿到undefined,赋值到state后render方法中打印自然也是undefined。 - 非法渲染对象:你后续直接将
response.data赋值给plans后直接在JSX中输出{ plans },React不支持直接把对象作为子元素渲染,因此抛出对象非法的报错。 - 组件名笔误:你定义的组件类名为
Home,最后导出时写的是withRouter(Landing),类名与导出名不匹配,运行时也会触发报错。
修复后的完整代码
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import httpService from '../../httpService'; class Home extends Component { constructor(props) { super(props); this.state = { plans: [], loading: true, }; } componentDidMount() { this.fetchPlans(); } async fetchPlans() { try { const response = await httpService.get('/plans'); // 用正确的字段名解构取值 const { paymentPlans } = response.data; this.setState({ plans: paymentPlans, loading: false }); } catch (e) { console.log(e); this.setState({ loading: false }); } } render() { const { plans, loading } = this.state; if (loading) return <div>加载中...</div>; return ( <div> {/* 遍历数组取出字段渲染,不要直接渲染整个对象 */} {plans.map((planItem, index) => ( <div key={index}> <h3>{planItem.planName}</h3> <p>价格:{planItem.price}</p> <p>时长:{planItem.months}个月</p> <p>说明:{planItem.description}</p> </div> ))} </div> ); } } // 修正导出的组件名 export default withRouter(Home);
补充说明
如果你的paymentPlans是单个对象而非数组,不需要遍历,直接按字段取值渲染即可:
render() { const { plans, loading } = this.state; if (loading) return <div>加载中...</div>; return ( <div> <h3>{plans.planName}</h3> <p>价格:{plans.price}</p> <p>时长:{plans.months}个月</p> <p>说明:{plans.description}</p> </div> ) }
内容的提问来源于stack exchange,提问作者Cudos
相关产品推荐
相关产品推荐

