为什么我的React页面未渲染数组?Mongoose获取的数据控制台可打印但页面不显示
数组对象无法渲染问题排查与修正
定位到的渲染失败根因
- 状态字段读写完全错位
初始化 state 时定义的列表存储字段为fruits: [],但接口请求拿到数据后,执行setState时把数据存到了从未在 state 中声明的produce字段上;渲染阶段又去读取同样未在 state 中定义的this.state.fruit字段执行map循环,既无法拿到接口返回的数据,还会因为读取undefined的map方法直接触发运行时报错,阻断页面渲染。 - 接口请求地址拼写错误
代码中请求地址写为http://localhos:2000/api/fruits,将localhost错拼为localhos,正常状态下该请求无法连通后端服务;你能在控制台打印到接口返回数据,大概率是实际调试时临时修正了地址拼写。 - 加载状态逻辑缺失
初始化 state 设置了loading: true,但渲染阶段没有对应状态判断,数据返回前页面没有加载反馈,也没有对接口异常、空数据场景做兜底处理。 - 组件命名不符合React规范
类组件使用小写开头的produce作为组件名,按照React官方规范,类组件需要使用大驼峰命名。
修正后可正常运行的代码
class Produce extends Component { constructor() { super(); this.state = { loading: true, fruits: [] }; } componentDidMount() { // 修正拼写错误的请求地址 fetch('http://localhost:2000/api/fruits') .then(response => response.json()) .then(resData => { // 对齐state字段,将接口返回数据存入fruits字段,同时更新加载状态 this.setState({ fruits: resData, loading: false }); console.log(resData); }) .catch(error => { console.log(error); // 接口报错时同步更新加载状态,避免页面卡在加载中 this.setState({ loading: false }); }); } render() { // 加载状态兜底 if (this.state.loading) { return <div>数据加载中...</div> } return ( <div> <ul> this text above shows // 对齐state字段,读取实际存储的fruits数据渲染列表 {this.state.fruits.map(d => ( <li key={d.id}>{d.fruit}</li> ))} </ul> </div> ); } }
内容的提问来源于stack exchange,提问作者Ahmed Abdi
相关产品推荐
相关产品推荐

