Spring Boot返回对象数组到React时axios赋值state失效问题
问题原因
代码存在两个核心问题导致状态赋值失败:
- Promise链式调用断链:第一个
.then()里仅执行了console.log(response),没有返回任何值,后续链式调用的第二个.then()拿到的入参是undefined,根本无法获取接口响应内容 - 数据取值路径错误:从控制台打印的响应结构可以看到,目标药品数组不在axios响应的根层级,实际存储路径是
响应对象.data.medicineList,直接给Meds赋整个响应对象或者undefined都不符合预期
修复方案
调整接口请求的回调逻辑,去掉多余的链式then,拿到响应后按正确路径取值再赋值,同时补充错误捕获,修正后的componentDidMount代码如下:
componentDidMount(){ axios.get("http://localhost:8081/api/v1/ivm/customer/inventory/medicines") .then(response => { console.log(response) // 按响应结构提取目标药品数组 const medicineList = response.data.medicineList this.setState({Meds: medicineList}); }) .catch(err => { console.error("药品列表请求失败:", err) }) }
表格渲染参考
状态赋值成功后,直接在render方法里遍历this.state.Meds生成表格行即可,示例代码:
render() { return ( <div> <table border="1" cellPadding="8"> <thead> <tr> <th>药品名称</th> <th>药品类型</th> <th>售价</th> </tr> </thead> <tbody> {this.state.Meds.map((item, idx) => ( <tr key={idx}> <td>{item.name}</td> <td>{item.type}</td> <td>{item.price}</td> </tr> ))} </tbody> </table> </div> ) }
注意:如果后端返回的药品数据有唯一id,遍历时key最好用唯一id代替数组下标,提升渲染性能。
内容的提问来源于stack exchange,提问作者GIRIDHAR B
相关产品推荐
相关产品推荐

